Jump to content

preg_match is always returning true, problem with UTF-8?


SuperBlue

Recommended Posts

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

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".

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.

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();
}

Archived

This topic is now archived and is closed to further replies.

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