Solved

PHP preg_match

Posted on 2014-10-22
3
133 Views
Last Modified: 2014-10-23
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";
}
0
Comment
Question by:mfinocc
3 Comments
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 40398326
Remove the spaces

if (!preg_match("/^[0-9]{4}[A-Z]{1}$/",$name)) {

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40398331
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

0
 

Author Comment

by:mfinocc
ID: 40398361
Thanks!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question