PHP:将 preg_replace 与 htmlentities 结合使用

标签 php regex

我正在将 RSS 写入 JSON 解析器,作为其中的一部分,我需要在任何标签上使用 htmlentities()在描述标签内找到。目前,我正在尝试使用 preg_replace(),但我有点吃力。我当前的(非工作)代码如下所示:

$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("$1").'</description>';
$rawFeed = preg_replace($pattern, $replace, $rawFeed);

如果您对此也有更优雅的解决方案,请分享。谢谢。

最佳答案

简单。使用 preg_replace_callback:

function _handle_match($match)
{
    return '<description>' . htmlentities($match[1]) . '</description>';
}

$pattern = "/\<description\>(.*?)\<\/description\>/is";
$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);

它接受任何回调类型,所以也接受类中的方法。

关于PHP:将 preg_replace 与 htmlentities 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/128350/

相关文章:

php - 模拟php POST输入

php - 在 PHP 中选择用户名和密码正确的条目比仅选择用户名和检查密码的优势是什么?

php - 根据段数对数组值进行排序

php - 为什么 PHP 模板不能从 mySQL 数据库中检索正确的数据?

javascript - 正则表达式字符串不以特殊字符开头或结尾

php - 为每个版本的 API 使用单独的目录

regex - 使用 sed 更改文件扩展名

python - 如何编写脚本来迭代搜索文档并根据模式返回结果

regex - F# 正则表达式匹配链

regex - Oracle Regex 替换负前瞻