Formatting Phone Numbers in PHP

前端 未结 20 2297
面向向阳花
面向向阳花 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 20:02

    This is a US phone formatter that works on more versions of numbers than any of the current answers.

    $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)
    {
        print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
    }
    

    And here is a breakdown of the regex:

    Cell: +1 999-(555 0001)
    
    .*          zero or more of anything "Cell: +1 "
    (\d{3})     three digits "999"
    [^\d]{0,7}  zero or up to 7 of something not a digit "-("
    (\d{3})     three digits "555"
    [^\d]{0,7}  zero or up to 7 of something not a digit " "
    (\d{4})     four digits "0001"
    .*          zero or more of anything ")"
    

    Updated: March 11, 2015 to use {0,7} instead of {,7}

提交回复
热议问题