Simple check for 4 or 5 digits not working

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
andymcc77
Forum Newbie
Posts: 2
Joined: Tue Nov 17, 2009 3:30 pm

Simple check for 4 or 5 digits not working

Post by andymcc77 »

Simple check for 4 or 5 digits not working

The code below allows more than 5 digits to be entered.

Code: Select all

 
 if (!$error && !preg_match("/[0-9]{4,5}$/", trim($tel_prefix))) {
   $error = true;
   $message = "Telephone Prefix is 4/5 digits "; 
   $focus = "tel_prefix"; 
 } 
 
I am new to regex, any ideas ?, i thought {4,5} would ensure more than 5 digits is not
allowed ?

Thanks,
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Simple check for 4 or 5 digits not working

Post by Apollo »

This regexp only checks if the strings ends with 4 or 5 digits (because of the $ at the end).

Add a ^ in the beginning to restrict the string (from beginning to end) to 4-5 digits:

Code: Select all

preg_match("/^[0-9]{4,5}$/",$number)
andymcc77
Forum Newbie
Posts: 2
Joined: Tue Nov 17, 2009 3:30 pm

Re: Simple check for 4 or 5 digits not working

Post by andymcc77 »

I thought I had tried that, but I did as you said and it works now!

I obviously must have got it wrong somewhere, works now anyway, thanks for the help!
Post Reply