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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.