使用Preg Match检查字符串是否包含下划线


Using Preg Match to check if string contains an underscore

我试图检查字符串是否包含下划线-谁能解释下面的代码有什么问题

    $str = '12_322';
    if (preg_match('/^[1-9]+[_]$/', $str)) {
       echo 'contains number underscore';
    }

在您的正则表达式中,[_]$意味着下划线位于字符串的末尾。这就是为什么它和你的不匹配。

如果您只想检查字符串中任何地方的下划线检查,则:

if (preg_match('/_/', $str)) {

如果要检查字符串必须由数字和下划线组成,则

if (preg_match('/^[1-9_]+$/', $str)) {  // its 1-9 you mentioned

但是对于您的示例输入12_322,这个也可以很方便:

if (preg_match('/^[1-9]+_[1-9]+$/', $str)) {

您需要取出$,因为下划线不是您输入的最后一个字符。你可以试试这个regex:

'/^[1-9]+_/'

PS:下划线不是一个特殊的正则表达式字符,因此不需要在字符类中。