tags:

views:

43

answers:

4

Hi,

Has anyone got a good regex that will match on both UK and USA numbers?

It would need to cater for uk prefixes like +44 and also the US equivalent.

Does anyone know of such an expression?

Cheers

Paul

A: 

You could use the following to validate UK mobile numbers:

<?php
function valid_UK_mobile($gsm) {
    return preg_match("/^00447\d{9}$|^07\d{9}$|^447\d{9}$|^[+]447\d{9}$/", $gsm); // +447XXXXXXXXX, 447XXXXXXXXX, 07XXXXXXXXX, 00447XXXXXXXXX
}
echo (valid_UK_mobile("+447000000000") ? 'OK' : 'NOT OK') . '<br />'; //success
echo (valid_UK_mobile("447000000000") ? 'OK' : 'NOT OK') . '<br />'; //success
echo (valid_UK_mobile("07000000000") ? 'OK' : 'NOT OK') . '<br />'; //success
echo (valid_UK_mobile("00447000000000") ? 'OK' : 'NOT OK') . '<br />'; //success
echo (valid_UK_mobile("00440000000000") ? 'OK' : 'NOT OK') . '<br />'; // fail
?>

something weird with stackoverflow, the code - http://paste-it.net/public/o060a91/

Kyle Hudson
A: 

You could even use:

^\s*(?(020[7,8]{1})?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3})?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$ (http://regexlib.com/REDetails.aspx?regexp_id=495)

or

^(?:(?<1>[(])?(?[2-9]\d{2})(?(1)[)])(?(1)(?<2>[ ])|(?:(?<3>[-])|(?<4>[ ])))?)?(?[1-9]\d{2})(?(AreaCode)(?:(?(1)(?(2)[- ]|[-]?))|(?(3)[-])|(?(4)[- ]))|[- ]?)(?\d{4})(?:[ ]?[xX]?(?\d{2,4}))?$ (http://regexlib.com/REDetails.aspx?regexp_id=537)

Kyle Hudson
A: 

Take a look at the Regexp::Common library on the CPAN.

http://search.cpan.org/dist/Regexp-Common/

Andy Lester