查找字符串中的第一个"invalid"字符(清理电话号码)



我们正在更新一个系统,其中注释已添加到包含电话号码的字段中。使用 PHP,我们试图清理字段并将它们一分为二。一个用于电话号码,另一个用于便笺。数字总是在前,注释在后。

我们并不过分关心生成的电话号码的确切格式。当用户更新其配置文件时,可能会强制清理它们。数字为美国格式。

举几个例子。我想可能还有其他变化:

"(123) 456-7890 Betty's cell"
becomes
"(123) 456-7890" and "Betty's cell"
"123-456-7890  Betty's cell
becomes
"123-456-7890" and "Betty's cell"
"456-7890  Betty's cell
becomes
"456-7890" and "Betty's cell"
"456-7890 ext. 123  Betty's cell
becomes
"456-7890 ext. 123" and "Betty's cell"

有效的电话号码字符将"+()-0123456789 ",为了使事情进一步复杂化,我们需要允许"ext."我可以清理现有数据,以便所有分机变体都相同。我们很乐意找到字符串中第一个"无效"字符的位置并将其拆分在那里。

一直在搜索,但似乎找不到适合这种情况的任何内容。感谢任何建议。
非常感谢!

您可以使用正则表达式,如下所示;

^([+()-0-9 ]*)([A-Za-z' ]*)$

组1 结果始终是数字,组 2 结果将是名字和姓氏 您可以检查 https://regex101.com/r/PhEQNH/1/

$re = '/^([+()-0-9 ]*)([A-Za-z' ]*)$/';
$str = '123-456-7890  Betty's cell
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);

您可以使用正则表达式并preg_match

function splitPhoneNotes($s) {
preg_match("~^([d() +-]+(?:ext.[d() -]+)?)(.*)~", $s, $res);
return [
"phone" => trim($res[1]),
"note" => trim($res[2]) 
];
}
// Sample inputs
$arr = [
"(123) 456-7890 Betty's cell",
"123-456-7890  Betty's cell",
"456-7890  Betty's cell",
"+1 (324) 456-7890 ext. 33 Betty's cell",
];
// Apply the function to each of the inputs
$res = array_map('splitPhoneNotes', $arr);
// Results
print_r($res);

看到它在 repl.it 上运行

相关内容

最新更新