仅限 <code></code> 上的 php htmlentities!

标签 php html implode

我只想对要剥离的内容中的内容运行 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/

相关文章:

php - MySQL PHP 数据库连接

javascript - jquery/JS 动态控件的简单数据绑定(bind)

javascript - 我不明白如何使用 document.getElementById (‘id’ ).onclick

php - 在 mysqlquery 和 php 方面需要帮助

php - 当用户在 YII 中注销时,与 session 关联的行将被删除

php - 获取调用该函数的行?

php memcached 统计页面,使用 PECL::memcache

html - 为什么我的背景图片不显示?

php - 如何使用 MySQL 将一条记录的值分解为多行?

php - 对内爆值调用函数?