Php 正则表达式模式以查找所有<;代码></代码>;块,即使它们有CSS类

Php 正则表达式模式以查找所有<;代码></代码>;块,即使它们有CSS类,php,regex,preg-match-all,Php,Regex,Preg Match All,我的WordPress functions.php文件中有以下代码。其目的是在保存时检查所有post内容,查看是否存在块,然后对标记内的内容执行htmlspecialchars操作 // Encode htmlspecialchars when saving posts function FilterCodeOnSave( $content, $post_id ) { // test data $textToScan = $content; // the regex

我的WordPress functions.php文件中有以下代码。其目的是在保存时检查所有post内容,查看是否存在
块,然后对标记内的内容执行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;
}
对于
块没有类的实例,该代码工作得非常好。我的问题是,我使用带CSS类和不带CSS类的
标记,并且我需要htmlspecialchars操作应用于所有代码标记,无论它们是否有类

我需要说一些类似“find”的词,这样搜索字符串将同时找到普通代码标记和具有类的代码标记,例如

希望这是有意义的

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

非常感谢,, 詹姆斯怎么样

// the regex pattern (case insensitive & multiline)
$search = "~<code.*?>(.*?)</code>~is";
//正则表达式模式(不区分大小写&多行)
$search=“~(.*)”
~is”;
您应该将正则表达式更改为:

$search = "~<code\s[^>]*.(.*?)<\/code>~is";
$search=“~]*。(.*?)是”;

$search=“~(.*?”
~is”;
除非你把
*
弄得像这样懒,
*?
我会最大化,但恐怕我没有足够的声誉。再次感谢。@Maxime他是这个意思。*?有效,所以最好在有人否决之前纠正你的答案:PI知道这很简单。。。PHP新手在这里!再次感谢艾勒,我会在期限到期时将此标记为答案。
$search = "~<code\s.*?>(.*?)</code>~is";