使用preg_replace在PHP字符串中查找电话号码的终极方法 [英] Ultimate way to find phone numbers in PHP string with preg_replace

查看:84
本文介绍了使用preg_replace在PHP字符串中查找电话号码的终极方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在正在处理一个项目,在该项目中,我们有大量的文本字符串,我们必须本地化电话号码,并使它们对于Android手机而言可点击.

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

+61 8 9000 7911

+2783 207 5008

+2783 207 5008

+ 82-2-806-0001

+82-2-806-0001

+56(2)509 69 00

+56 (2) 509 69 00

+44(0)1625 500125

+44 (0)1625 500125

+1(305)409 0703

+1 (305)409 0703

031-704 98 00

031-704 98 00

+46 31 708 50 60

+46 31 708 50 60

推荐答案

也许是这样的:

/(\+\d+)?\s*(\(\d+\))?([\s-]?\d+)+/

  • (\+\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.

      这篇关于使用preg_replace在PHP字符串中查找电话号码的终极方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆