Ultimate way to find phone numbers in PHP string with preg_replace

谁说我不能喝 提交于 2019-11-28 11:34:59

问题


working on a project right now where we have large amount of text strings that we must localize phone numbers and make them clickable for android phones.

The phone numbers can be in different formats, and have different text before and after them. Is there any easy way of detecting every kind of phone number format? Some library that can be used?

Phone numbers can show like, has to work with all these combinations. So that the outcome is like

<a href="tel:number">number</a>

+61 8 9000 7911

+2783 207 5008

+82-2-806-0001

+56 (2) 509 69 00

+44 (0)1625 500125

+1 (305)409 0703

031-704 98 00

+46 31 708 50 60


回答1:


Not sure that there is a library for that. Hmmmm. Like any international amenities, telephone numbers are standardised and there should be a format defining telephone numbers as well. E.164 suggests recommended telephone numbers: http://en.wikipedia.org/wiki/E.164 . All open-source decoding libraries are built from reading these standard formats, so it should be of some help if you really cant find any existing libs




回答2:


Perhaps something like this:

/(\+\d+)?\s*(\(\d+\))?([\s-]?\d+)+/
  • (\+\d+)? = A "+" followed by one or more digits (optional)
  • \s* = Any number of space characters (optional)
  • (\(\d+\))? = A "(" followed by one or more digits followed by ")" (optional)
  • ([\s-]?\d+)+ = One or more set of digits, optionally preceded by a space or dash

To be honest, though, I doubt that you'll find a one-expression-to-rule-them-all. Telephone numbers can be in so many different formats that it's probably impractical to match any possible format with no false positives or negatives.




回答3:


I guess this might do it for these cases?

preg_replace("/(\+?[\d-\(\)\s]{7,}?\d)/", '<a href="tel:$1">number</a>', $str);

Basicly I check if it may start on +. It doesn't have to. Then I check if it got numbers, -, (, ) and spaces with at least 8 cases so it doesn't pick low non-phone numbers.




回答4:


Try the following:

preg_match_all('/\+?[0-9][\d-\()-\s+]{5,12}[1-9]/', $text, $matches);

or:

preg_match_all('/(\+?[\d-\(\)\s]{8,20}[0-9]?\d)/', $text, $matches);


来源:https://stackoverflow.com/questions/10141295/ultimate-way-to-find-phone-numbers-in-php-string-with-preg-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!