Jump to content

[SOLVED] Preg_match and regex validation not working


mtscales

Recommended Posts

Basically I have the following code to validate a user's entry in a form.

 

if(preg_match('/^[\w|_|\-|@|\s\']{1,100}$/',$_POST[FormTextField])){ 
Code for good form entry
}
else{ 
Code for bad form entry
}

 

I want to allow all alphanumeric characters as well as _ - @ ' and spaces.  The script seems to work it allows all the characters I want APART FROM THE ' (single quote) character.  It also seems to disallow unwanted characters.

 

Could anyone suggest a reason why if FormTextField contains a ' my script thinks it is a bad entry?

 

I am new to regex and preg_match (and php for that matter) so may be approaching this completely the wrong way.  Any Advice much appreciated.

You don't need the "|" character in a character class separating the values -- they're "OR" by default in a class.  Also underscore is included in the \w class.

 

Try:

/^[\w\s@\'-]{1,100}$/

 

If you're getting errors from single quotes, I suspect that magic quotes might be on and the pattern is finding [/b]\'[/b] and failing on the slash.

Thanks a lot I used stripslashes on the String from the form (magic quotes was on) changed my pattern for preg_match to

 

"/^[\w\-@\s']{1,100}$/"

 

and it works like I want it to (just had to change some single quotes to double in my html).

 

Is it best to have magic quotes on or off?

 

Is it best to have magic quotes on or off?

 

I prefer them off, but to keep your code portable (you don't know what server it will be running on in the future) you should check get_magic_quotes_gpc() before using stripslashes().

 

Note: You don't have to escape the hyphen if you put it at the beginning or end of a character class.

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.