php validate string with preg_match

霸气de小男生 提交于 2019-12-10 13:32:16

问题


I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.

I tried to search on google but I could not find anything usefull.

Can anybody help?

Thank you !


回答1:


Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'

So:

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good
}

Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.




回答2:


$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1

$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0



回答3:


You can use preg_replace($pattern, $replacement, $subject):

if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
  echo "Detect non valid character inside the string";
}

The idea is to remove any valid chars, if the result is NOT empty do the code.



来源:https://stackoverflow.com/questions/14056803/php-validate-string-with-preg-match

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