我只想对要剥离的内容中的内容运行 htmlentities()
我编写了一个函数,它接受一个字符串并查找
之间的内容
function parse_code($string) {
<pre><code> // 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;
}
}
</code></pre>
但是,我需要一些有关实际运行 htmlentities() 的函数的帮助;对
中的内容进行 implode() 将其全部重新组合在一起。例如,假设我们有下面的字符串。
<div class="myclass" rel="stuff"> things in here </div> <code> only run htmlentites() here so strip out things like < > " ' & </code> <div> things in here </div>
再一次,该函数需要保持字符串的所有内容相同,但只修改
的内容并运行 htmlentities()
最佳答案
您可以使用自定义回调函数来简化此操作:
$html = preg_replace_callback(
"@ (?<= <code>) .*? (?= </code>) @six",
"htmlentities_cb", $html
);
function htmlentities_cb($matches) {
return htmlentities($matches[0], ENT_QUOTES, "UTF-8");
}
匹配封闭代码标签的语法称为 lookbehind and lookahead assertion 。它简化了回调并避免了稍后的 implode(),因为断言匹配本身不会成为 $matches[0] 的一部分。 @six 用于不区分大小写的标签匹配,并允许正则表达式中存在空格以使其更具可读性。
关于仅限 <code></code> 上的 php htmlentities!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4989017/