preg_match中只有字母数字和一个特殊字符regex


Only Alphanumeric and one special charcter regex in preg_match

$str = 'test-test-test-test''50-test-37447';
     if(preg_match('/[a-zA-Z0-9-]/',$str,$matches)){
         echo "<pre>true";print_r($matches);echo "</pre>";
     }else{
         echo "<pre>false";print_r($matches);echo "</pre>";
     }

它总是返回真的吗?我哪里错了?

它返回true,因为正则表达式调用该集合中的任何一个字符(因此从一开始的t是第一个匹配(。

如果您希望整个字符串仅由这些字符组成,请使用:

^[a-zA-Z0-9-]*$

^$标记分别表示字符串的开始和结束,*表示前一个"对象"的零个或多个。因此,这意味着整个字符串必须由零个或多个指定的字符集组成。

这会导致'字符在测试字符串中的匹配失败。