我正在将 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/