Link to home
Start Free TrialLog in
Avatar of mfinocc
mfinocc

asked on

PHP preg_match

I need to validate a string for these criteria...

Must be 5 characters
First 4 characters must be 0-9
Fifth character must be A-Z

How do I make this work?

$name = test_input($_POST["name"]);
if (!preg_match("/^[0-9] {4} [A-Z] {1}$/",$name)) {
  $nameErr = "not allowed";
}
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You may find regular expressions easier to understand (decipher) if you write them like this -- with comments and explanations.
$rgx
= '#'        // REGEX DELIMITER
. '^'        // AT START OF STRING
. '['        // START CHARACTER CLASS
. '0-9'      // RANGE OF CHARACTERS 0-9
. ']'        // END OF CHARACTER CLASS 
. '{4}'      // EXACTLY FOUR OF THESE IN THE CLASS
. '[A-Z]'    // A CHARACTER CLASS OF ALPHABETIC CHARACTERS
. '{1}'      // EXACTLY ONE OF THESE IN THE CLASS
. '$'        // AT THE END OF THE STRING
. '#'        // REGEX DELIMITER
. 'i'        // OPTIONAL - CASE-INSENSITIVE
;

Open in new window

Avatar of mfinocc
mfinocc

ASKER

Thanks!