Search code examples
phpregexinternationalizationphone-number

formatting local phone numbers into international (knowing countries)


I use an SMS API to send confirmation code to phone.
Its parameters requires me to set the visitors phone number format into international, for example +9912345678 instead of 012 345 678.
Is there a php class (without Composer) that would do it for me (could not find anything so far on GG), considering I know user's both country (from a select input) and number (from a text input) he submitted on the previous webpage?


Solution

  • I previously used this library (without composer) and worked well: https://github.com/davideme/libphonenumber-for-PHP

    You only have to include in your php PhoneNumberUtil.php and that file knows what else needs to include.

    You can format a number like this:

    $swissNumberStr = "044 668 18 00";
    $phoneUtil = PhoneNumberUtil::getInstance();
    try {
        $swissNumberProto = $phoneUtil->parseAndKeepRawInput($swissNumberStr, "CH");
        var_dump($swissNumberProto);
    } catch (NumberParseException $e) {
        echo $e;
    }
    echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL)
    

    Check demo.php to see more examples on how to use library.