2

我只想对 <code> 中的内容运行 htmlentities() 以剥离 </code>

我写了一个函数,它接受一个字符串并在 <code> </code> 之间找到内容

function parse_code($string) {

        // test the string and find contents with <code></code>
        preg_match('@<code>(.*?)</code>@s', $string, $matches);

            // return the match if it succeeded
            if($matches) {
                return $matches[1];
            }else {
                return false;
            }
    }

但是,我需要一些有关将实际运行 htmlentities(); 的功能的帮助;在 <code> </code> 中的内容上,然后 implode() 将它们重新组合在一起。例如,假设我们有下面的字符串。

<div class="myclass" rel="stuff"> 这里的东西 </div>
<code> 只在这里运行 htmlentites() 所以去掉像 < > " ' & </code> 这样的东西
<div> 里面的东西 </div>

再一次,该函数需要保持字符串的所有内容相同,但只修改和运行 <code> </code> 的内容的 htmlentities()

4

1 回答 1

5

您可以使用自定义回调函数来简化此操作:

$html = preg_replace_callback(
     "@  (?<= <code>)  .*?  (?= </code>)  @six",
     "htmlentities_cb", $html
);

function htmlentities_cb($matches) {
    return htmlentities($matches[0], ENT_QUOTES, "UTF-8");
}

匹配封闭代码标记的语法称为lookbehind 和lookahead assertion。它简化了回调并在以后避免了 implode(),因为断言匹配本身不会成为 $matches[0] 的一部分。@six 用于不区分大小写的标记匹配,并允许正则表达式中的空格使其更具可读性。

于 2011-02-14T05:20:20.407 回答