PHP:使用带有htmlentities的preg_replace

时间:2008-09-24 16:57:12

标签: php regex

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

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

如果你有更优雅的解决方案,请分享。感谢。

2 个答案:

答案 0 :(得分: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);

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

答案 1 :(得分:0)

更优雅的解决方案是使用SimpleXML。或者是第三方库,例如XML_Feed_ParserZend_Feed来解析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看起来不同,这就是为什么使用我提到的上述库之一是有意义的。

相关问题