【问题标题】:extract phone number from string (resume) in php从php中的字符串(简历)中提取电话号码
【发布时间】:2012-06-19 14:09:42
【问题描述】:

需要从简历中提取电话号码。它可以以多种方式嵌入,可以在自己的行中:

714-555-1212

或排长队

1212 main st fullerton ca 92835  949.555.1212

想提取成数组——区号,3位,4位

这是我目前所拥有的,但是当同一线路上除了电话号码之外还有其他号码时,它不起作用:

function get_phone_number ($string){
    $lines = explode("\n",trim($string));
    foreach ($lines as $value){ 
        //echo "Line: ".$value."<BR>";

        preg_match_all('!\d+!', $value, $matches);
        if (strlen($matches[0][0])=='3' && strlen($matches[0][1])=='3' && strlen($matches[0][2])=='4') { 
            $area_code = $matches[0][0];

        }
    }
    return $area_code;
}

【问题讨论】:

  • 然后呢?你想让我们为你写吗?
  • 这不是 phpfreaks(您将有更好的机会为您编写代码)。至少先试试。
  • 到目前为止我有这个,但是当同一行有其他数字时它不起作用,比如街道地址数字:
  • 你只支持 NANP 格式的数字吗?

标签: php string extract


【解决方案1】:
<?php
$areaCodes = array();
$threeDigits = array();
$fourDigits = array();

preg_match_all('/(\d{3})-(\d{3})-(\d{4})/',$content,$matches);

if(count($matches[1])>0)
{
    for($i=0; $i<count($matches[1]); $i++)
    {
        array_push($areaCodes,$matches[1][$i]); 
        array_push($threeDigits,$matches[2][$i]);   
        array_push($fourDigits,$matches[3][$i]);    
    }
}

preg_match_all('/\((\d{3})\)-(\d{3})-(\d{4})/',$content,$matches);

if(count($matches[1])>0)
{
    for($i=0; $i<count($matches[1]); $i++)
    {
        array_push($areaCodes,$matches[1][$i]); 
        array_push($threeDigits,$matches[2][$i]);   
        array_push($fourDigits,$matches[3][$i]);    
    }
}
preg_match_all('/(\d{3}).(\d{3}).(\d{4})/',$content,$matches);

if(count($matches[1])>0)
{
    for($i=0; $i<count($matches[1]); $i++)
    {
        array_push($areaCodes,$matches[1][$i]); 
        array_push($threeDigits,$matches[2][$i]);   
        array_push($fourDigits,$matches[3][$i]);    
    }
}

preg_match_all('\((\d{3})\).(\d{3}).(\d{4})/',$content,$matches);

if(count($matches[1])>0)
{
    for($i=0; $i<count($matches[1]); $i++)
    {
        array_push($areaCodes,$matches[1][$i]); 
        array_push($threeDigits,$matches[2][$i]);   
        array_push($fourDigits,$matches[3][$i]);    
    }
}
print_r($areaCodes);
print_r($threeDigits);
print_r($fourDigits);

【讨论】:

  • 当电话号码用点分隔时有效。但有时它的 (714) 555-1212 或 714-555-1212 或 714 555-1212
  • 我根据您的要求编辑了答案。必要时进行编辑并使用 or 运算符。你应该可以从这个蓝图中弄清楚。
  • 谢谢,它工作得很好,除了它在这个上不起作用 - (760) 617-7147 - 我对正则表达式很不满意,需要添加什么才能识别括号周围的区号?谢谢
  • 如果您觉得这个答案有帮助,请点击旁边的 ✔ mark it as accepted
猜你喜欢
  • 2023-03-16
  • 2013-10-01
  • 2016-11-07
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多