Php 如何让正则表达式将字符串中的问号仅视为文本

Php 如何让正则表达式将字符串中的问号仅视为文本,php,regex,preg-replace,preg-match,Php,Regex,Preg Replace,Preg Match,我不知道如何描述这一个,所以我希望标题是适当的 我在WordPress functions.PHP文件中使用下面的PHP代码,在每次保存帖子时对标记中的所有内容运行htmlspecialchars function FilterCodeOnSave( $content, $post_id ) { // test data $textToScan = $content; // the regex pattern (case insensitive & multiline) $searc

我不知道如何描述这一个,所以我希望标题是适当的

我在WordPress functions.PHP文件中使用下面的PHP代码,在每次保存帖子时对标记中的所有内容运行htmlspecialchars

function FilterCodeOnSave( $content, $post_id ) {

// test data
$textToScan = $content;

// the regex pattern (case insensitive & multiline)
$search = "~<code.*?>(.*?)</code>~is";

// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
//print_r($matches);

// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
        $replace = htmlspecialchars($match, ENT_NOQUOTES);
        // now replace the previously found CODE block
        $textToScan = str_replace($match, $replace, $textToScan);
}

// output result
return $textToScan;
}
例如,当我的标记中包含的代码是PHP时,使用上述函数会出现问题

当我使用上述代码时,之后的任何代码片段都会得到不同的处理,例如,我的函数将忽略这是一个段落。

并返回这是一个段落。这是一个段落,而不是


我相信这与代码块中包含的PHP代码中的问号有关。如果我删除了中的问号,您就不需要在之前全部使用preg\u match\u。最好的方法是使用preg_replace_callback,使用一种模式来查找代码标记之间的内容:

function FilterCodeOnSave($content) {
    return preg_replace_callback('~<code[^>]*>\K.*?(?=</code>)~is',
        function ($m) { return htmlspecialchars($m[0], ENT_NOQUOTES); },
        $content);
}

问号是正则表达式中的特殊字符。要将它们视为文字字符串,只需使用反斜杠\Hi对其进行转义,谢谢,但代码现在什么都不做。代码块中的所有标记都保持原样,不会转换为它们的实体名称。@user2979032:我已根据您的情况调整了代码。