How to check, if a php string contains only english letters and digits?

前端 未结 9 1580
既然无缘
既然无缘 2020-11-30 01:33

In JS I used this code:

if(string.match(/[^A-Za-z0-9]+/))

but I don\'t know, how to do it in PHP.

相关标签:
9条回答
  • 2020-11-30 02:19

    PHP can compare a string to a regular expression using preg_match(regex, string) like this:

    if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
        // $string contains only English letters and digits
    }
    
    0 讨论(0)
  • 2020-11-30 02:23
    if (preg_match('/^[\w\s?]+$/si', $string)) {
        // input text is just English or Numeric or space
    }
    
    0 讨论(0)
  • 2020-11-30 02:25

    Have a look at this shortcut

    if(!preg_match('/[^\W_ ] /',$string)) {
    
    }
    

    the class [^\W_] matches any letter or digit but not underscore . And note the ! symbol . It will save you from scanning entire user input .

    0 讨论(0)
提交回复
热议问题