Jump to content

[SOLVED] preg_match for letters and numbers only


crackpanda

Recommended Posts

~^[A-Za-z0-9]*$~

 

Edit: You don't need regex to check if a string contains only numbers and letters (Is alphanumeric), you could just as well use ctype_alnum(). Personally I'd use that.

 

It would be much faster as well, not that it would matter if you're only using it once.. But running a benchmarking test shows that ctype_alnum is about 6-12 times faster.

Also note that using regex patterns like in this thread could also match strings with values like "987Uyp3\n" (note the newline). To prevent this, one could either make use of the D modifier (which in essence prevents the dollar sign from matching end newlines) or make use of \z:

 

example:

~^[a-z0-9]*$~iD

 

-or-

 

~^[a-z0-9]*\z~i

 

Both eliminate this issue. More info on stuff like \z is found here. Info on PCRE modifiers (like D) can be found here.

 

Finally, also be aware that since the quantifier is * (zero or more), this could match a string with nothing in it. If a range of characters is desireable, you can either use intervals ( like for example {3,8} - Minimum 3 characters, maximum ) or even better, simply check the length of the string using strlen first, then if it satisfies the desired length, go forth with the checking of alpha numerics.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.