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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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