Solved

PHP preg_match

Posted on 2014-10-22
3
144 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 110

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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
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…
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.

717 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