Page 1 of 1

My introduction into regular expressions.

Posted: Mon Sep 19, 2005 1:22 am
by s.dot
Edit: Actually, this whole post is an edit. :P

I'm getting into regexes, so I might have more than my fair share of questions.

Firstly, I developed a scenario in my head. I want to see if a user has entered 2 consecutive numbers for their age. If they enter 3 numbers, then it's wrong. If they enter 1 number then it's wrong.

I've developed this regular expression.

Code: Select all

<?
$string = 'Scott is 20 years old.';
echo $string;
echo "<BR><BR>";

if(preg_match("/\d{2}\d/",$string))
{
	echo "You have entered an incorrect age.";
} ELSE
{
	echo "You have entered a correct age.";
}
?>
This returns as I expect it to for more than 2 numbers. However if I put I'm 9 years old, it still returns true. How do I limit it to TWO numbers only?

Edit #2:

Code: Select all

preg_match("/(\d)|(\d{3})/",$string)
My second attempt. Also failed.

Posted: Mon Sep 19, 2005 5:30 am
by timvw
But not it returns true as soon it matches two characters in the range of 0-9... Fe: mike99xxx is valid too...

I would write the following: match something that starts with 2 numbers and then end: ^\d{2}$

Posted: Mon Sep 19, 2005 6:13 am
by n00b Saibot
I will teach you with your example :)

Code: Select all

<? 
$string = 'Scott is 20 years old.';
echo $string; 
echo "<BR><BR>"; 

if(preg_match("#[^\d\w]\d{2}[^\d\w]#",$string))
 echo "You have entered a correct age.";
else 
 echo "You have entered an incorrect age.";
?>
My expression will match only 2 digit number and nothing else. not even mike99xxx :wink:

Posted: Mon Sep 19, 2005 6:53 am
by sweatje
I think you are looking for

Code: Select all

$regex = '/\b\d{2}\b/';

Posted: Mon Sep 19, 2005 7:34 am
by shoebappa
Isn't \b a word boundary? So the above would match "I am 10 years old"

^ outside of [] means starts with, and $ means ends with so:

Code: Select all

$regex = '/^\d{2}$/';
and the other above #[^\d\w]\d{2}[^\d\w]# matches whitespace and symbols so " 12 " or ":12:"

Posted: Mon Sep 19, 2005 8:46 am
by sweatje
shoebappa wrote:Isn't \b a word boundary?"
Yes, zero width assertion for a word boundary.
shoebappa wrote: So the above would match "I am 10 years old"
The original poster showed a similar string as an example, so I assumed that extracting from the middle of a string context was what they were looking for.

Posted: Mon Sep 19, 2005 11:29 am
by s.dot
I didn't need anything specific. So all of your guys responses were a learning experience for me. Thank you all.

Posted: Mon Sep 19, 2005 5:11 pm
by shoebappa
Heh, I'd just woken up and obviously didn't read the post very well : ) It's hard for me to figure out what the hell I was thinking... Silly Me.

Glad you learned something anyhoo.