crackpanda Posted September 28, 2009 Share Posted September 28, 2009 Hello, could someone please assist me by showing how to put together a preg_match statement for letters and numbers only, no spaces? Quote Link to comment Share on other sites More sharing options...
Alex Posted September 28, 2009 Share Posted September 28, 2009 ~^[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. Quote Link to comment Share on other sites More sharing options...
crackpanda Posted September 28, 2009 Author Share Posted September 28, 2009 Thanks Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted September 28, 2009 Share Posted September 28, 2009 Just be aware of the 'locale' pitfalls of ctype.. you can read up about that here. Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted September 28, 2009 Share Posted September 28, 2009 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.