Why is the following regex failing?

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

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Why is the following regex failing?

Post by impulse() »

Code: Select all

$word = "stephen";

if(ereg("^[a-z][A-Z][0-9]$", $word))
  echo "Good";
else
  echo "Bad";
It's returning "Bad". But I would expect it to return "Good" as it meets the condition of the regex, as far as I can see.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

your character classes are only set to match a string of 3 characters

try: ^[a-zA-Z0-9]+$

but further to that, you should really consider using the PCRE regex functions. They're the defacto standard. Shoud that be the case, you'd want something with delimiters:

Code: Select all

preg_match('/^[a-zA-Z0-9]+$/',$word)
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

Thanks that worked.

I'm currently reading through chapters on regex in my books at the minute. I always chose not to read about it because I found regex scary and thought it was more of a choice thing to learn. But from the past 30 minutes I've been reading about it seems pretty cool and not as scary as I once thought it looked.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

regex is a strange and fickle beast, but like most things is just a collection of small patterns.

Stay with it, I hear it gives you super powers.
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

The comic was so inspiring.

I feel like a trainee superhero already.

A bit off-topic but have you ever read BOFL?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

BOFL?
Post Reply