简体   繁体   中英

regex phone number validation with PHP

This is another question about a previous question I had asked yesterday . I want user to be allowed to type US phone numbers in the following formats.

(800)-555-1212

800-555-1212

and have it only check the database for numbers 8005551212

I've seen that regex like /^[\\+]?([0-9]*)\\s*\\(?\\s*([0-9]{3})?\\s*\\)?[\\s\\-\\.]*([0-9]{3})[\\s\\-\\.]*([0-9]{4})[a-zA-Z\\s\\,\\.]*[x\\#]*[a-zA-Z\\.\\s]*([\\d]*)/

may work but I'm not certain how to implement it into the code from the link I provided

I'm new to php and know nothing about regex. Any help is appreciated.

This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.

    /**
     * @param $number
     *
     * @return bool
     */
    function validatePhoneNumber($number) {
        $formats = [
            '###-###-####', '####-###-###',
            '(###) ###-###', '####-####-####',
            '##-###-####-####', '####-####', '###-###-###',
            '#####-###-###', '##########', '#########',
            '# ### #####', '#-### #####'
        ];

        return in_array(
            trim(preg_replace('/[0-9]/', '#', $number)),
            $formats
        );
    }

if javascript is ok can go with

<script type="text/javascript">
function matchClick() {
  var re = new RegExp("Your regex here");
  if (document.formname.phone.value.match(re)) {
     alert("Ok");
     return true;
  } else {
     alert("Not ok");
     return false;
  }
} 
</script>

call this function onsubmit of form or onblur of textbox

If you have doubt about your regex you can validate it at http://www.regular-expressions.info/javascriptexample.html

您可以使用此模式

\\(?\\d{3,3}\\)?-\\d{3,3}-\\d{4,4}

Try this,

<?php
    $t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
    $arr=preg_match($t,'(800)-555-1212',$mat);
    $arr=preg_match($t,'800-555-1212',$mat);
    print_r($mat);
?>

Tested here

Re: Rohan Kumar's solution

<?php
$t='/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
$arr=preg_match($t,'(800)-555-1212',$mat);
$arr=preg_match($t,'800-555-1212',$mat);
print_r($mat);
?>

It does address the issue of fake phone numbers such as 800-123-2222. Real phone numbers have a first digit of at least "2". While the other solutions do the format correctly, they don't address the issue of people putting in phone numbers like 800-000-1234, which would be correct in the other solutions provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM