Editing form to sanitize/validate phone number

本秂侑毒 提交于 2019-12-05 04:31:05
Kyle

Have you looked into PHP's preg_replace function? You can strip out any non-numeric character by using preg_replace('/[^0-9]/', '', $_POST['phone']).

Once you filter out the character data, you can always check to see if it is of a desired length:

$phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
if(strlen($phone) === 10) {
    //Phone is 10 characters in length (###) ###-####
}

You can also use PHP's preg_match function as discussed in this other SO question.

There are a couple of ways to do it... examples:

// If you want to clean the variable so that only + - . and 0-9 can be in it you can:
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);

// If you want to clean it up manually you can:
$phone = preg_replace('/[^0-9+-]/', '', $_POST['phone']);

// If you want to check the length of the phone number and that it's valid you can:
if(strlen($_POST['phone']) === 10) {
    if (!preg_match('/^[0-9-+]$/',$var)) { // error } else { // good }
}

Obviously some edits may need to be made dependent on the country and other misc factors.

You could try using preg_replace to filter out any non-numeric characters, then you can check the length of whats remaining to see if its a phone number (should be either 7,9 or maybe 10 digits)

// remove anything thats not a number from the string
function only_numbers($number) { return preg_replace('/[^0-9]/', '', $number) };
// test that the string is only 9 numbers long
function isPhone($number) { return strlen(only_numbers($number)) == 9; }

Just make sure to use the only_numbers value when using the value after validating it.

-Ken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!