Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regular expression minimum and maximum length doesn't work as expected

I want to create a regular expression in PHP, which will allow to user to enter a phone number in either of the formats below.

345-234 898

345 234-898

235-123-456

548 812 346

The minimum length of number should be 7 and maximum length should be 12.

The problem is that, the regular expression doesn't care about the minimum and maximum length. I don't know what is the problem in it. Please help me to solve it. Here is the regular expression.

if (preg_match("/^([0-9]+((\s?|-?)[0-9]+)*){7,12}$/", $string)) {
echo "ok";
} else {
echo "not ok";
}

Thanks for reading my question. I will wait for responses.

like image 691
Muhammad Sohail Avatar asked Aug 22 '26 17:08

Muhammad Sohail


2 Answers

You should use the start (^) and the end ($) sign on your pattern

$subject = "123456789";
    $pattern = '/^[0-9]{7,9}$/i';
    if(preg_match($pattern, $subject)){
        echo 'matched';
    }else{
        echo 'not matched';
    }
like image 60
Socheatha Tey Avatar answered Aug 25 '26 08:08

Socheatha Tey


You can use preg_replace to strip out non-digit symbols and check length of resulting string.

$onlyDigits = preg_replace('/\\D/', '', $string);
$length = strlen($onlyDigits);
if ($length < 7 OR $length > 12)
  echo "not ok";
else
  echo "ok";
like image 31
Ulugbek Umirov Avatar answered Aug 25 '26 06:08

Ulugbek Umirov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!