【问题标题】:PHP Regex to extract phone number from + to first non-numberPHP正则表达式从+提取电话号码到第一个非数字
【发布时间】:2015-05-22 03:24:31
【问题描述】:

编辑:我这样做是因为我提供的数据有数百个这种格式的换行符分隔条目,我需要将微格式合并到地址数据中。因此,如果提供的字符串如下,我需要输出:

<p><span itemprop="telephone">+1 800 123 456</span> (toll free) from overseas</p>

--

我需要一个正则表达式从以下格式中提取电话号码:

+1 800 123 456(免费电话)来自海外

我提供的数据一直以这种格式输入,非常有效,一个正则表达式可以获取所有内容,包括“+”到第一个非数字字符。

【问题讨论】:

  • 你能提供你的尝试吗?
  • 而不是明确地提取电话号码。你能用preg_replace('/[^0-9\+]/', '', $phone_number);删除所有不是数字或加号的东西吗?

标签: php regex


【解决方案1】:

如果你想使用正则表达式,你可以使用这样的东西:

\+[\d\s]+

$re = '/(\+[\d\s]+)/'; 
$str = "+1 800 123 456 (toll free) from overseas\n"; 

preg_match_all($re, $str, $matches);

另一方面,您可以使用castis 的建议,使用 preg_replace 将不需要的字符替换为空字符串并保留其余字符,例如:

preg_replace('/[\D\+]/', '', $phone_number); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多