PHP very strict complex string validation using preg_match

谁都会走 提交于 2019-12-25 04:34:08

问题


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:

  1. my knowledge of regex isn't that great in the first place
  2. 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:

  1. Make sure the input string is encoded with UTF-8 encoding.

  2. 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)

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!