[英]php regex, extract phone numbers from string?
i am having a small problem with my regex which i use to extract phone numbers from a strong 我的正则表达式有一个小问题,我用它来提取强大的电话号码
<?php
$output = "here 718-838-3586 there 1052202932 asdas dasdasd 800-308-4653 dasdasdasd 866-641-6949800-871-0999";
preg_match_all('/\b[0-9]{3}\s*[-]?\s*[0-9]{3}\s*[-]?\s*[0-9]{4}\b/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
?>
output 产量
Array
(
[0] => 718-838-3586
[1] => 1052202932
[2] => 800-308-4653
[3] => 866-641-6949
[4] => 800-871-0999
)
this work fine but it returns 1052202932 as one of result which i don't need . 这工作正常,但它返回1052202932作为我不需要的结果之一。
actually i don't know where is the missing part in my pattern . 实际上我不知道我的模式中缺少的部分在哪里。
? ? in regex means {0,1} and you need exactly 1 occurence of '-' in your pattern
在正则表达式中意味着{0,1},你需要在你的模式中出现' - '
preg_match_all('/\b[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b/',$output,$matches);
For more info http://www.php.net/manual/en/regexp.reference.repetition.php 欲了解更多信息, 请访问http://www.php.net/manual/en/regexp.reference.repetition.php
The ?
的
?
after each [-]
is making the -
optional. 在每个
[-]
之后进行-
可选。 If you want it to be required you can just remove the ?
如果你想要它,你可以删除
?
which will make it required. 这将使它成为必需。 Also,
[-]
is equivalent to -
so I got rid of the unnecessary character class: 另外,
[-]
相当于-
所以我摆脱了不必要的角色类:
preg_match_all('/\b[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b/',$output,$matches);
You can also replace all of the [0-9]
with \\d
to shorten it a bit further: 您还可以用
\\d
替换所有[0-9]
以进一步缩短它:
preg_match_all('/\b\d{3}\s*-\s*\d{3}\s*-\s*\d{4}\b/',$output,$matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.