在电话号码后立即使用逗号分割字符串
尝试分割字符串,但我不想“删除”我正在搜索的内容...
该字符串看起来像这样:
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()
是要使用的东西。我还应该使用其他东西吗?
Trying to split a string, but I don't want to "remove" what I'm searching for...
The string Looks like this:
MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,
I want to split the string after the phone number, but I don't want to remove the number.
Right now, I have this:
preg_split("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x", $string)
But that outputs:
Array
(
[0] => MDVB, 94010,
[1] => KHII, 94015,
[2] => POONHY, 94010,
)
I thought preg_split()
was the thing to use. Is there something else I should be using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该使用 preg_match_all() 来提取字符串的部分。
输出:
You should use preg_match_all() to extract portions of your string.
Outputs:
您可以使用
PREG_SPLIT_DELIM_CAPTURE
选项,这将导致捕获并返回分隔符模式中的括号表达式。结果数组:
我相信这是您正在寻找的行为。
You could use the
PREG_SPLIT_DELIM_CAPTURE
option which will cause the parenthesized expression in the delimiter pattern to be captured and returned as well.Resulting array:
I believe this is the behavior you were looking for.
结果:
results:
你最好像这样使用 preg_match_all :
输出:
You should better use preg_match_all like this:
OUTPUT:
preg_split()
不是一个可靠的验证工具。如果您需要验证,请使用preg_match_all()
。您的电话号码可能具有不同的前导格式这一事实与拆分过程无关 - 识别电话号码的结尾,使用\K
忘记以前匹配的字符,然后匹配不需要的分隔逗号和可选空间。 演示输出:
preg_split()
is not a reliable tool for validation. If you need validation, usepreg_match_all()
. The fact that your phone numbers may have varied leading formats is irrelevant to the splitting process -- identify the end of the phone number, use\K
to forget previously matched characters, then match the unneeded delimiting comma and optional space. DemoOutput: