sardonicgem Posted May 16, 2008 Share Posted May 16, 2008 Hello folks, I'm trying to check a form field to make sure the user inputs an alphanumeric entry only. The preg_match function does not seem to be the solution. Any ideas on how to go about this? Quote Link to comment Share on other sites More sharing options...
Orio Posted May 16, 2008 Share Posted May 16, 2008 Best solution for you would be using ctype_alnum. It's more efficient than using a regular expression, and it does the job. Regex way: if(preg_match("/[a-z0-9]*/i", $str)) { //Str is valid } Orio. Quote Link to comment Share on other sites More sharing options...
sardonicgem Posted May 16, 2008 Author Share Posted May 16, 2008 The form field is case sensitive. Also I'm not quite sure how preg_match works. php.net indicates: preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. So suppose my string was "Pa55word" preg_match( '[:alnum:]',"Pa55word") So according to the return value conditions, will preg_match stop searching after P? Quote Link to comment Share on other sites More sharing options...
teng84 Posted May 16, 2008 Share Posted May 16, 2008 that is why your making a pattern if you make a pattern that will only search for a certain words then your conclusion is applicable here but if your pattern tries to match not just a word then thats another way Quote Link to comment Share on other sites More sharing options...
sardonicgem Posted May 17, 2008 Author Share Posted May 17, 2008 Thanx for the response teng84 but I'm not quite sure I understand what you're talking about. In my case above will preg_match stop searching after the letter P? If so, is there a function that you know of that can search all characters of the input string and confirm that they are all [:alnum:]? Quote Link to comment Share on other sites More sharing options...
Orio Posted May 17, 2008 Share Posted May 17, 2008 Yeah yeah my bad. Should be: <?php if(preg_match("/^[a-z0-9]*$/i", $str)) { //Str is valid } ?> But I still recommend using the ctype_*() functions. Orio. Quote Link to comment Share on other sites More sharing options...
sardonicgem Posted May 17, 2008 Author Share Posted May 17, 2008 Thank you Orio. I ended up using ctype_alnum(). 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.