Formatting Phone Numbers in PHP

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

    Don't reinvent the wheel! Import this amazing library:
    https://github.com/giggsey/libphonenumber-for-php

    $defaultCountry = 'SE'; // Based on the country of the user
    $phoneUtil = PhoneNumberUtil::getInstance();
    $swissNumberProto = $phoneUtil->parse($phoneNumber, $defaultCountry);
    
    return $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL);
    

    It is based on Google's library for parsing, formatting, and validating international phone numbers: https://github.com/google/libphonenumber

提交回复
热议问题