Formatting Phone Numbers in PHP

前端 未结 20 2291
面向向阳花
面向向阳花 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: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) . '
    '; } // ************************************************************************ // 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; }

提交回复
热议问题