' & " inside a php regexp
Would this be the correct regexp to allow A-Z a-z 0-9 and symbols #&()-\;,.'" and spaces?
I'm struggling with the ' and " inside the regexp. Is what I've开发者_JAVA百科 done correct? Note the \' and \". It just doesn't seem right. Whats the right way to do it?
if (preg_match('/^[a-z0-9#&()-\;,.\'\" ]+$/i', $username) )
{
echo "Good";
}
else
{
echo "Bad";
}
The dash should be escaped, and the double quote does not need to be. Bizarrely, you need to quadruple escape the backslash before the semi-colon. Otherwise it is interpreted as if you are escaping the semi-colon and is ignored.*
'/^[a-z0-9#&()\-\\\\;,.\'" ]+$/i'
You can also put an unescaped dash at the beginning of a character class, though that's a bit obscure and may momentarily confuse someone unaware of that option. It works because a dash at the start cannot be part of a valid character range, so it can only be a literal dash character.
'/^[-a-z0-9#&()\\\\;,.\'" ]+$/i'
* The \\\\; is reduced to \\; by PHP before the regex engine sees it. The regex engine then reduces \\; to \;. Thus, four backslashes! A single backslash \; becomes simply ;. The same goes for \\;—PHP reduces that to \; and then the regex engine interprets \; as a plain semi-colon ;. No less than four will do.
Actually, I lied. You can get away with three backslashes. But then you're abusing the leniency of PHP's parser a bit. Four is definitely best.
Brackets also needed to be escaped
'/^[a-z0-9#&\(\)\-;,.\'" ]+$/i'
加载中,请稍侯......
精彩评论