SuperBlue Posted November 7, 2011 Share Posted November 7, 2011 I had some code that I'm pretty sure used to work, basically something like the below. if (preg_match("/[a-zA-Z0-9]+/", $_POST['title'])) { echo $_POST['title'];exit(); } Now i just don't get why it always returns true, even when entering special characters like "!#%?".. The only thing which comes to mind, is that i recently made a move to UTF-8.. Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 7, 2011 Share Posted November 7, 2011 I had some code that I'm pretty sure used to work, basically something like the below. if (preg_match("/[a-zA-Z0-9]+/", $_POST['title'])) { echo $_POST['title'];exit(); } Now i just don't get why it always returns true, even when entering special characters like "!#%?".. The only thing which comes to mind, is that i recently made a move to UTF-8.. The regular expression will return true if there is AT LEAST ONE alphanumeric character. All the other characters can be anything. So, "A!@#$%^&*()" will return true because of the letter "A". Quote Link to comment Share on other sites More sharing options...
SuperBlue Posted November 7, 2011 Author Share Posted November 7, 2011 You are right, strange though, because i was pretty sure i tested this when i first wrote it.. I think i have this thing figured out, i need to have e ^ for start, and $ for end, otherwise it will return true if a matching pattern was found anywhere in the string. if (preg_match("/^[a-zA-Z0-9]+$/", $_POST['title'])) { echo $_POST['title'];exit(); } Thanks.. Well now i finally get when to include the start and end stuff. Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 7, 2011 Share Posted November 7, 2011 Yes, that will work but, typically, if you are wanting to ensure that all characters are within a defined set a more efficient expression is to look for any characters NOT in the defined set. Just put the carat ("^") inside the character class to indicate any character not in the class. But, in this logic a true means disallowed characters were found, so you want to check for false result if (!preg_match("/[^a-zA-Z0-9]/", $_POST['title'])) { echo $_POST['title'];exit(); } 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.