Search code examples
phpregexmaxminimum

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.


Solution

  • 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";