Regex模式查找所有<;代码></代码>;块,即使它们有CSS类


Regex pattern to find all <code></code> blocks even if they have a CSS class

我的WordPress functions.php文件中有以下代码。其目的是在保存时检查所有发布内容,以查看是否存在<code></code>块,然后对标记内的内容执行htmlspecialchars操作。

// Encode htmlspecialchars when saving posts
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
    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;
}

对于<code></code>块没有类的实例,该代码工作得非常好。我的问题是,我在有CSS类和没有CSS类的情况下都使用<code></code>标记,并且我需要htmlspecialchars操作来应用于所有代码标记,无论它们是否有类。

我需要说一些类似于"find<code(这里有或没有任何内容)>"的话,这样搜索字符串将同时找到纯代码标记和具有类的代码标记,例如<code class="language-html"></code>

希望这是有道理的。

此外,我知道regex不是这里许多人推荐的解决方案,所以如果你有更好的方法来实现结果,请随时提出建议。

非常感谢,James

您应该将正则表达式更改为:

$search = "~<code's[^>]*.(.*?)<'/code>~is";

$search = "~<code's.*?>(.*?)</code>~is";

怎么样?

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