Note that there are some explanatory texts on larger screens.

plurals
  1. POValidating US phone number with php/regex
    text
    copied!<p><strong>EDIT:</strong> <em>I've mixed and modified two of the answers given below to form the full function which now does what I had wanted and then some... So I figured I'd post it here in case anyone else comes looking for this same thing.</em></p> <pre><code>/* * Function to analyze string against many popular formatting styles of phone numbers * Also breaks phone number into it's respective components * 3-digit area code, 3-digit exchange code, 4-digit subscriber number * After which it validates the 10 digit US number against NANPA guidelines */ function validPhone($phone) { $format_pattern = '/^(?:(?:\((?=\d{3}\)))?(\d{3})(?:(?&lt;=\(\d{3})\))?[\s.\/-]?)?(\d{3})[\s\.\/-]?(\d{4})\s?(?:(?:(?:(?:e|x|ex|ext)\.?\:?|extension\:?)\s?)(?=\d+)(\d+))?$/'; $nanpa_pattern = '/^(?:1)?(?(?!(37|96))[2-9][0-8][0-9](?&lt;!(11)))?[2-9][0-9]{2}(?&lt;!(11))[0-9]{4}(?&lt;!(555(01([0-9][0-9])|1212)))$/'; //Set array of variables to false initially $valid = array( 'format' =&gt; false, 'nanpa' =&gt; false, 'ext' =&gt; false, 'all' =&gt; false ); //Check data against the format analyzer if(preg_match($format_pattern, $phone, $matchset)) { $valid['format'] = true; } //If formatted properly, continue if($valid['format']) { //Set array of new components $components = array( 'ac' =&gt; $matchset[1], //area code 'xc' =&gt; $matchset[2], //exchange code 'sn' =&gt; $matchset[3], //subscriber number 'xn' =&gt; $matchset[4], //extension number ); //Set array of number variants $numbers = array( 'original' =&gt; $matchset[0], 'stripped' =&gt; substr(preg_replace('[\D]', '', $matchset[0]), 0, 10) ); //Now let's check the first ten digits against NANPA standards if(preg_match($nanpa_pattern, $numbers['stripped'])) { $valid['nanpa'] = true; } //If the NANPA guidelines have been met, continue if($valid['nanpa']) { if(!empty($components['xn'])) { if(preg_match('/^[\d]{1,6}$/', $components['xn'])) { $valid['ext'] = true; } } else { $valid['ext'] = true; } } //If the extension number is valid or non-existent, continue if($valid['ext']) { $valid['all'] = true; } } return $valid['all']; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload