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
https://forums.phpfreaks.com/topic/230383-preg_match-characters-slipping-through/
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.';

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.

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.