Formatting Phone Numbers in PHP

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

提交回复
热议问题