Jump to content

preg_match - characters slipping through


mottwsc

Recommended Posts

This should be simple, but it doesn't seem to work.  This preg_match should not be allowing other characters like # % and others, but it does.  In other words, it does not hit the error message section if a pound sign or percent sign is entered in the 'answer' field on the form.  I'm trying to only allow the characters that are listed: letters, numbers, single quote, exclamation, period, comma, space, dash and question mark.  Can anyone see why this wouldn't be working?  Thanks!

 

$answerClean = trim($_POST['answer']);
if( !preg_match("/^[A-Za-z0-9'!., -?]{2,150}$/", $answerClean) )     
{ 
$message = 
$message."You have not provided a valid answer for the question.";
}

Link to comment
Share on other sites

It's because your regex is flawed. I would suggest to change it to the following. You need to escape all the special regex characters that are reserved.

 

$answerClean = trim($_POST['answer']);
if(!preg_match('#^[A-Za-z0-9\'!\., \-?]{2,150}$#', $answerClean))     
   $message .= 'You have not provided a valid answer for the question.';

Link to comment
Share on other sites

I understand the escaping of special characters, but why did you wrap everything in hash signs (#)?

 

That is probably his preference (it is mine as well). You can use just about any character to deliniate your regex expression. But, the problem with your original pattern was the period which as a wildcard will match any character. That is why it needed to be escaped.

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.