Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

MSISDN validation

Simple but effective format and validation of MSISDN (GSM number):
    /**
     * Format the mobile phone
     *
     * @param string $phone
     * @param string $countryCode
     * @param string $mobliePhoneLength
     * @param array $allowedPrefixes
     * @return string $phone
     */
    public static function formatMobilePhone(string $phone, string $countryCode, string $mobliePhoneLength, array $allowedPrefixes = [])
    {
        $phone = preg_replace("/[^0-9]/", "", $phone);
        $phone = ltrim($phone, '0');
        if ($mobliePhoneLength != strlen($phone)) {
            $phone = $countryCode . $phone;
        }

        if ($allowedPrefixes) {
            $phoneWithoutCountryCode = substr($phone, strlen($countryCode));
            $allowedPrefix = false;
            foreach($allowedPrefixes as $prefix) {
                if (substr($phoneWithoutCountryCode, 0, strlen($prefix)) == $prefix) {
                    $allowedPrefix = true;
                    break;
                }
            }
        } else {
            $allowedPrefix = true;
        }

        if ($allowedPrefix && strlen($phone) == $mobliePhoneLength) {
            return $phone;
        }
        return false;
    }