PHP:将preg_replace与htmlentities结合使用

时间:2020-03-06 14:40:29  来源:igfitidea点击:

我正在向JSON解析器写RSS,作为其一部分,我需要在description标记内找到的任何标记上使用htmlentities()。目前,我正在尝试使用preg_replace(),但是我为此付出了一些努力。我当前的(无效)代码如下所示:

$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("").'</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);

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

更为优雅的解决方案是采用SimpleXML。或者第三方库(例如XML_Feed_Parser或者Zend_Feed)来解析提要。

这是一个SimpleXML示例:

<?php
$rss = file_get_contents('http://rss.slashdot.org/Slashdot/slashdot');
$xml = simplexml_load_string($rss);

foreach ($xml->item as $item) {
    echo "{$item->description}\n\n";
}
?>

请记住,RSS,RDF和Atom看起来有所不同,这就是为什么使用我提到的上述库之一有意义的原因。