Search code examples
phpregexpreg-match

Validate for more than one format with preg_match


I have a phone number field that is set up to validate using preg_match:

function ValidPhone($phone) {
    return preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', trim($phone));
}

This ensures that phone numbers are entered in the xxx-xxx-xxxx format and that it's numeric.

I'm not very familiar with regexp; can anyone tell me how I'd expand this to allow more than one format? i.e. xxx xxx xxxx or xxx.xxx.xxxx or (xxx) xxx-xxxx

Thanks.


Solution

  • I think the easiest solution would be to just strip out everything that isn't numeric first:

    function ValidatePhone($phone) {
        $phone = preg_replace('/\D+/', '', $phone);
        return strlen($phone) == 10;
    }
    

    Since you are validating the format, and not the content, this should do it:

    function ValidatePhone($phone) {
        $patterns = array(
            '\d{3}([-\. ])\d{3}\g{-1}\d{4}',
            '\(\d{3}\) \d{3}-\d{4}'
            );
    
        $phone = trim($phone);
    
        foreach ($patterns as $pattern) {
            if (preg_match('/^' . $pattern . '$/', $phone))
                return true;
        }
    
        return false;                                                                                                                   
    }