[英]php - regex to extract phone numbers from a string
i am having a small problem with my regex which i use to extract italian phone numbers from a string 我的正则表达式有一个小问题,我用来从字符串中提取意大利语电话号码
<?php
$output = "+39 3331111111";
preg_match_all('/^((00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}$/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
?>
it works correctly if the $output
is just the telephone number but if i change the output with a more complex string like: 如果$output
只是电话号码,但如果我用更复杂的字符串更改输出,它可以正常工作:
(eg. $output = "hello this is my number +39 3331111111 how are you?";
) (例如。 $output = "hello this is my number +39 3331111111 how are you?";
)
it will not extract the number, how can i change my regex to extract the number? 它不会提取数字,我怎样才能改变我的正则表达式来提取数字?
Remove the anchors and add word boundaries \\b
at the right places: 删除锚点并在正确的位置添加单词边界\\b
:
((\b00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}\b
^ ^
See regex demo . 请参阅正则表达式演示 。
See IDEONE demo : 请参阅IDEONE演示 :
$output = "hello this is my number +39 3331111111 how are you?";
preg_match_all('/((\b00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}\b/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
You can also use non-capturing groups (to "clean" the output a bit) and a greedy ?
您还可以使用非捕获组(“清理”输出一点)和贪婪?
instead of lazy ??
而不是懒惰??
(the regex will be a bit more efficient): (正则表达式将更有效):
(?:(?:\b00|\+)39[\. ]?)?3\d{2}[\. ]?\d{6,7}\b
^^ ^^ ^ ^ ^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.