Formatting Phone Numbers in PHP

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

    Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.

    Using it like this,

    use libphonenumber\NumberParseException;
    use libphonenumber\PhoneNumber;
    use libphonenumber\PhoneNumberFormat;
    use libphonenumber\PhoneNumberUtil;
    
    $phoneUtil = PhoneNumberUtil::getInstance();
    
    $numberString = "+12123456789";
    
    try {
        $numberPrototype = $phoneUtil->parse($numberString, "US");
    
        echo "Input: " .          $numberString . "\n";
        echo "isValid: " .       ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
        echo "E164: " .           $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
        echo "National: " .       $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
        echo "International: " .  $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
    } catch (NumberParseException $e) {
        // handle any errors
    }
    

    you will get the following output:

    Input: +12123456789
    isValid: true
    E164: +12123456789
    National: (212) 345-6789
    International: +1 212-345-6789
    

    I'd recommend using the E164 format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()).

    As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE through the code above, you will get

    Input: 1-800-JETBLUE
    isValid: true
    E164: +18005382583
    National: (800) 538-2583
    International: +1 800-538-2583
    

    Neato.

    It works just as nicely for countries other than the US. Just use another ISO country code in the parse() argument.

提交回复
热议问题