Solved

PHP preg_match

Posted on 2014-10-22
3
125 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 108

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

746 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now