.Stealth Posted May 11, 2010 Share Posted May 11, 2010 Having some trouble with regex as usual, why do they make it so hard? All i want is to check that a string has only text, numbers and spaces in it, that is all. It can contain spaces anywhere at all and as many of them. All the examples I've seen just show how to do one space at the beginning/end, not how to do as many as you want. I've tried all sorts of things but most just completely break it. Here's what I've got: function alphaNumTextCheck($string){ if(preg_match('/[^a-z0-9]/', $string)){ return TRUE; } else{ return FALSE; } } That only checks for text and numbers, if i add a space into the string it comes back FALSE. Can anybody help? Thanks. Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 11, 2010 Share Posted May 11, 2010 You have your True/False backwards. That regex tests to see if there are any characters NOT in the list specified. Since you don't want those characters you should be returning false. Adding a space in the character list works fine for me. Also, assuming you want to allow capital letters you need to add A-Z, or better yet, just make the regex case insensitive using the "i" parameter. Lastly, no need to create an If/Else to return True/False since the preg_match will do that for you: function alphaNumTextCheck($string) { return (!preg_match('/[^a-z0-9 ]/i', $string)); } alphaNumTextCheck('word'); //Returns true alphaNumTextCheck('word123'); //Returns true alphaNumTextCheck(' word 123 '); //Returns true alphaNumTextCheck('word#123'); //Returns false alphaNumTextCheck('word:123'); //Returns false Quote Link to comment Share on other sites More sharing options...
.Stealth Posted May 11, 2010 Author Share Posted May 11, 2010 Ah right thanks alot! I didn't know just a simple space in the expression worked, i was trying \s Thanks again. 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.