PHP:使用带有htmlentities的preg_replace

Vir*_*dia 3 php regex

我正在写一RSSJSON parser,并作为其中的一部分,我需要使用htmlentities()的描述标签中找到的任何标记.目前,我正在尝试使用preg_replace(),但我正在苦苦挣扎.我当前的(非工作)代码如下所示:

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

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

Arm*_*her 7

简单.用途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);
Run Code Online (Sandbox Code Playgroud)

它接受任何回调类型,也接受类中的方法.