问题
I am trying to validate a string against the following regular expression which has been imposed upon me:
[-,.:; 0-9A-Z&@$£¥€'"«»‘’“”?!/\\()\[\]{}<>]{3}[-,.:; 0-9A-Z&@$£¥€'"«»‘’“”?!/\\()\[\]{}<>*=#%+]{0,157}
Can anybody help with writing a preg_match
in PHP to validate an input string against this? I am struggling because:
- my knowledge of regex isn't that great in the first place
- I see special characters in the regex itself which I feel sure PHP won't be happy about me inserting directly into a string (e.g. $£¥€)
In vain hope I just tried sticking it into preg_match
, escaping the double quotes, thus:
$ste = "Some string input";
if(preg_match("/[-,.:; 0-9A-Z&@$£¥€'\"«»‘’“”?!/\\()\[\]{}<>]{3}[-,.:; 0-9A-Z&@$£¥€'\"«»‘’“”?!/\\()\[\]{}<>*=#%+]{0,157}/",$ste))
{
echo "OK";
}
else
{
echo "Not OK";
}
Thanks in advance!!
回答1:
PHP will be perfectly happy with the "special" characters in the expression, provided you do the following:
Make sure the input string is encoded with UTF-8 encoding.
Make sure your PHP program file is saved using UFT-8 encoding. (and obviously you'll need to use UTF-8 encoding in all other parts of your system too, or you'll get borked characters showing up somewhere along the line, but that's outside the scope of this question)
Add the add the
u
modifier to the end of the regex pattern string to tell the regex parser to handle UTF-8 characters. ie:preg_match("/....../u", ...); ^ add this
Other than that, you've got it pretty much spot on already.
回答2:
You can do that:
if (preg_match('~^[ -"$&-),-<>?-\]{}£¥€«»‘’“”]{3}[ -\]{}£¥€«»‘’“”]{0,157}$~u', $ste))
echo 'OK';
else
echo 'Not OK';
I have added the "u" modifier for unicode, and reduced the size of the character classes using ranges (example:,-<
means all characters between ,
and <
in the unicode table).
But the most important, I have added anchors ^
and $
that means respectivly start and end of the string.
来源:https://stackoverflow.com/questions/19423869/php-very-strict-complex-string-validation-using-preg-match