user7128548 user7128548 - 18 days ago 5
PHP Question

PHP, Regex; only allow digits, letters and spaces

My string


  • may only contain digits, letters and spaces, nothing more

  • must contain at least zwo letters

  • must contain at least ten digits



How to echo something if my string doesn't match this pattern?

I hope any Regex expert can help me because I'm not very experienced with it.

Edit:

This is what I tried to far:

if (preg_match('/^[A-Z]+[0-9]+/', $myString)) {
echo "Error!";
}

Answer

This will do the job:

/^(?=(?:.*[a-z]){2})(?=(?:.*\d){10})[a-z0-9 ]+$/i

Using it in php:

if (preg_match('/^(?=(?:.*[a-z]){2})(?=(?:.*\d){10})[a-z0-9 ]+$/i', $myString)) {
    echo "OK!\n";
} else {
    echo "Error!\n";
}

Explanation:

/               : regex delimiter
  ^             : start of string
  (?=           : lookahead
    (?:         : non capture group
      .*[a-z]   : 0 or more any character followed by a letter
    ){2}        : end of group, must be present twice
  )             : end of lookahead
  (?=           : lookahaed
    (?:         : non capture group
      .*\d      : 0 or more any character followed by a digit
    ){10}       : end of group, must be present 10 times
  )             : end of lookahaed
  [a-z0-9 ]+    : character class, allowed characters are letters, digit and space
  $             : end of string
/i              : regex delimiter, case insensitive

You'll find usefull informations on lookahead here, on groups here