preg_match(): 编译失败:缺少字符类的终止 ]


preg_match(): Compilation failed: missing terminating ] for character class

if ( preg_match('/['.$i_word.']*( )*['.$p_word.']*/', $string, $match) ){
echo "<br>";
echo "more positive comment"; 

我收到同样的错误。在这里,无论是否与我的字符串匹配,我都绑定以匹配两个变量。但是收到错误:警告:preg_match((:编译失败:偏移量为 16 处的字符类缺少终止 ]

$i_word$p_word包含[或以'结尾,这使得preg_match()的第一个参数成为无效的正则表达式。

preg_quote()$i_word$p_word 一起使用,从中生成正确的正则表达式片段:

$regex = '/['.preg_quote($i_word, '/').']*( )*['.preg_quote($p_word, '/').']*/';
if (preg_match($regex, $string, $match)) {
    // success
}