Formatting Phone Numbers in PHP

前端 未结 20 2132
面向向阳花
面向向阳花 2020-11-28 19:39

I am working on an SMS app and need to be able to convert the sender\'s phone number from +11234567890 to 123-456-7890 so it can be compared to re

相关标签:
20条回答
  • 2020-11-28 19:50

    Here's my USA-only solution, with the area code as an optional component, required delimiter for the extension, and regex comments:

    function formatPhoneNumber($s) {
    $rx = "/
        (1)?\D*     # optional country code
        (\d{3})?\D* # optional area code
        (\d{3})\D*  # first three
        (\d{4})     # last four
        (?:\D+|$)   # extension delimiter or EOL
        (\d*)       # optional extension
    /x";
    preg_match($rx, $s, $matches);
    if(!isset($matches[0])) return false;
    
    $country = $matches[1];
    $area = $matches[2];
    $three = $matches[3];
    $four = $matches[4];
    $ext = $matches[5];
    
    $out = "$three-$four";
    if(!empty($area)) $out = "$area-$out";
    if(!empty($country)) $out = "+$country-$out";
    if(!empty($ext)) $out .= "x$ext";
    
    // check that no digits were truncated
    // if (preg_replace('/\D/', '', $s) != preg_replace('/\D/', '', $out)) return false;
    return $out;
    }
    

    And here's the script to test it:

    $numbers = [
    '3334444',
    '2223334444',
    '12223334444',
    '12223334444x5555',
    '333-4444',
    '(222)333-4444',
    '+1 222-333-4444',
    '1-222-333-4444ext555',
    'cell: (222) 333-4444',
    '(222) 333-4444 (cell)',
    ];
    
    foreach($numbers as $number) {
        print(formatPhoneNumber($number)."<br>\r\n");
    }
    
    0 讨论(0)
  • 2020-11-28 19:51

    this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.

    $raw_phone = preg_replace('/\D/', '', $raw_phone);
    $temp = str_split($raw_phone);
    $phone_number = "";
    for ($x=count($temp)-1;$x>=0;$x--) {
        if ($x === count($temp) - 5 || $x === count($temp) - 8 || $x === count($temp) - 11) {
            $phone_number = "-" . $phone_number;
        }
        $phone_number = $temp[$x] . $phone_number;
    }
    echo $phone_number;
    
    0 讨论(0)
  • 2020-11-28 19:52

    This function will format international (10+ digit), non-international (10 digit) or old school (7 digit) phone numbers. Any numbers other than 10+, 10 or 7 digits will remain unformatted.

    function formatPhoneNumber($phoneNumber) {
        $phoneNumber = preg_replace('/[^0-9]/','',$phoneNumber);
    
        if(strlen($phoneNumber) > 10) {
            $countryCode = substr($phoneNumber, 0, strlen($phoneNumber)-10);
            $areaCode = substr($phoneNumber, -10, 3);
            $nextThree = substr($phoneNumber, -7, 3);
            $lastFour = substr($phoneNumber, -4, 4);
    
            $phoneNumber = '+'.$countryCode.' ('.$areaCode.') '.$nextThree.'-'.$lastFour;
        }
        else if(strlen($phoneNumber) == 10) {
            $areaCode = substr($phoneNumber, 0, 3);
            $nextThree = substr($phoneNumber, 3, 3);
            $lastFour = substr($phoneNumber, 6, 4);
    
            $phoneNumber = '('.$areaCode.') '.$nextThree.'-'.$lastFour;
        }
        else if(strlen($phoneNumber) == 7) {
            $nextThree = substr($phoneNumber, 0, 3);
            $lastFour = substr($phoneNumber, 3, 4);
    
            $phoneNumber = $nextThree.'-'.$lastFour;
        }
    
        return $phoneNumber;
    }
    
    0 讨论(0)
  • 2020-11-28 19:56

    Here's a simple function for formatting phone numbers with 7 to 10 digits in a more European (or Swedish?) manner:

    function formatPhone($num) {
        $num = preg_replace('/[^0-9]/', '', $num);
        $len = strlen($num);
    
        if($len == 7) $num = preg_replace('/([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 $2 $3', $num);
        elseif($len == 8) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})/', '$1 - $2 $3', $num);
        elseif($len == 9) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})/', '$1 - $2 $3 $4', $num);
        elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 - $2 $3 $4', $num);
    
        return $num;
    }
    
    0 讨论(0)
  • 2020-11-28 19:56

    Another option - easily updated to receive a format from configuration.

    $numbers = explode("\n", '(111) 222-3333
    ((111) 222-3333
    1112223333
    111 222-3333
    111-222-3333
    (111)2223333
    +11234567890
        1-8002353551
        123-456-7890   -Hello!
    +1 - 1234567890
    ');
    foreach( $numbers AS $number ){
      echo comMember_format::phoneNumber($number) . '<br>';
    }
    
    // ************************************************************************
    // Format Phone Number
    public function phoneNumber( $number ){
      $txt = preg_replace('/[\s\-|\.|\(|\)]/','',$number);
      $format = '[$1?$1 :][$2?($2):x][$3: ]$4[$5: ]$6[$7? $7:]';
      if( preg_match('/^(.*)(\d{3})([^\d]*)(\d{3})([^\d]*)(\d{4})([^\d]{0,1}.*)$/', $txt, $matches) ){
        $result = $format;
        foreach( $matches AS $k => $v ){
          $str = preg_match('/\[\$'.$k.'\?(.*?)\:(.*?)\]|\[\$'.$k.'\:(.*?)\]|(\$'.$k.'){1}/', $format, $filterMatch);
          if( $filterMatch ){
            $result = str_replace( $filterMatch[0], (!isset($filterMatch[3]) ? (strlen($v) ? str_replace( '$'.$k, $v, $filterMatch[1] ) : $filterMatch[2]) : (strlen($v) ? $v : (isset($filterMatch[4]) ? '' : (isset($filterMatch[3]) ? $filterMatch[3] : '')))), $result );
          }
        }
        return $result;
      }
      return $number;
    }
    
    0 讨论(0)
  • 2020-11-28 19:57

    I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn't change length etc.)

    something like

    $in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4);
    

    should do it.

    0 讨论(0)
提交回复
热议问题