Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

preg replace - Ultimate way to find phone numbers in PHP string with preg_replace

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...