尝试拆分字符串,但我不想“删除”我正在搜索的内容...
字符串看起来像这样:
MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,
我想拆分电话号码后面的字符串,但我不想删除该号码。
现在,我有这个:
preg_split("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x", $string)
但是输出:
Array
(
[0] => MDVB, 94010,
[1] => KHII, 94015,
[2] => POONHY, 94010,
)
我认为
preg_split()
是可以使用的东西。我还应该使用其他东西吗?
您应该使用 preg_match_all() 来提取字符串的部分内容。
<?php
$string = "MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,";
$res = preg_match_all("/([A-Z]+,\s+\d+,\s+\(\d{3}\) \d{3}-\d{4})/",$string,$matches);
print_r($matches);
?>
输出:
Array
(
[0] => Array
(
[0] => MDVB, 94010, (555) 555-5555
[1] => KHII, 94015, (555) 555-5555
[2] => POONHY, 94010, (555) 555-5555
)
[1] => Array
(
[0] => MDVB, 94010, (555) 555-5555
[1] => KHII, 94015, (555) 555-5555
[2] => POONHY, 94010, (555) 555-5555
)
)
您可以使用
PREG_SPLIT_DELIM_CAPTURE
选项,这将导致捕获并返回分隔符模式中的括号表达式。
$parts = preg_split("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",
$string,
null,
PREG_SPLIT_DELIM_CAPTURE);
结果数组:
array(7) {
[0]=>
string(13) "MDVB, 94010, "
[1]=>
string(3) "555"
[2]=>
string(15) ", KHII, 94015, "
[3]=>
string(3) "555"
[4]=>
string(17) ", POONHY, 94010, "
[5]=>
string(3) "555"
[6]=>
string(1) ","
}
我相信这就是您正在寻找的行为。
$string = "MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,";
preg_match_all("/[A-Za-z]+, \d+, \(\d{3}\) \d{3}-\d{4}/", $string, $matches, PREG_SET_ORDER);
结果:
var_dump($matches);
array (
0 =>
array (
0 => 'MDVB, 94010, (555) 555-5555',
),
1 =>
array (
0 => 'KHII, 94015, (555) 555-5555',
),
2 =>
array (
0 => 'POONHY, 94010, (555) 555-5555',
),
)
你最好像这样使用 preg_match_all :
preg_match_all("/(.*?(?:\(? (?:\d{3})? \)? [\-\s] )? \d{3}-\d{4})[^,]*(?:,|$)\s*/x",
$string, $arr );
print_r($arr[1]);
输出:
Array
(
[0] => MDVB, 94010, (555) 555-5555
[1] => KHII, 94015, (555) 555-5555
[2] => POONHY, 94010, (555) 555-5555
)
preg_split()
不是可靠的验证工具。 如果您需要验证,请使用 preg_match_all()
。 您的电话号码可能具有不同的前导格式这一事实与拆分过程无关 - 识别电话号码的结尾,使用 \K
忘记之前匹配的字符,然后匹配不需要的分隔逗号和可选空格。 演示
$string = "MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,";
var_export(
preg_split('/\d{3}-\d{4}\K, ?/', $string, 0, PREG_SPLIT_NO_EMPTY)
);
输出:
array (
0 => 'MDVB, 94010, (555) 555-5555',
1 => 'KHII, 94015, (555) 555-5555',
2 => 'POONHY, 94010, (555) 555-5555',
)