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

时间:2016-02-15 03:47:45

标签: php regex

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

我收到同样的错误。在这里,我想要匹配两个变量是否匹配我的字符串。但是得到错误:警告:preg_match():编译失败:错过终止]对于偏移量为16的字符类

1 个答案:

答案 0 :(得分:0)

$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
}
相关问题