fazil tm fazil tm - 3 months ago 10
PHP Question

Php preg_match code for match the phone number

preg_match()
is not working in +(91) 111 11111

The code is

$number = +91 111 11111;

if (preg_match('/^\s*(?:\+?(\d{1,3}))?[(]\+[)]?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/', $number)) {
echo "True";
}


It is working. But not working in +91 (111) 11111

Answer

You may want to revisit your regex or try something like this:

<?php

    if (preg_match('#(^[\+\d][\d]{1,2})?(\()?([\d\s]*)?(\))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$#', $number)) {
        echo "True";
    }

UPDATE: CHANGED THE PATTERN

<?php

    // MATCHES: "+91 (111) 11111" OR "+91 111 11111" OR "91 (101) 23454" 
    // OR "+(91) (101) 23454" 
    // BUT NOT "1234500000000000000000000" OR "+121(121)38778" 
    $rx     = '#(^[\+\d](\()?[\d]{1,2})*(\))?(\s)(\()?([\d\s]*?)(\))?(\s)([\d\s]*?)$#';
    if (preg_match($rx, $number)) {
        //echo "True";
    }