PHP:使用preg_替换为htmlentities
我正在编写一个PHP:使用preg_替换为htmlentities,php,regex,Php,Regex,我正在编写一个RSS到JSON解析器,作为其中的一部分,我需要在description标记中找到的任何标记上使用htmlentities()。目前,我正在尝试使用preg_replace(),但我在这方面有点困难。我当前的(非工作)代码如下所示: $pattern[0] = "/\<description\>(.*?)\<\/description\>/is"; $replace[0] = '<description>'.htmlentities("$1").
RSS
到JSON解析器
,作为其中的一部分,我需要在description标记中找到的任何标记上使用htmlentities()
。目前,我正在尝试使用preg_replace()
,但我在这方面有点困难。我当前的(非工作)代码如下所示:
$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("$1").'</description>';
$rawFeed = preg_replace($pattern, $replace, $rawFeed);
$pattern[0]=“/\(.*?\/is”;
$replace[0]=''.htmlentities($1');
$rawFeed=preg_replace($pattern,$replace,$rawFeed);
如果你有一个更优雅的解决方案,请分享。谢谢。简单。使用
preg\u replace\u回调
:
function _handle_match($match)
{
return '<description>' . htmlentities($match[1]) . '</description>';
}
$pattern = "/\<description\>(.*?)\<\/description\>/is";
$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);
function\u handle\u match($match)
{
返回“.htmlentities($match[1])”;
}
$pattern=“/\(.*?\)/is”;
$rawFeed=preg_replace_回调($pattern,''u handle_match',$rawFeed);
它接受任何回调类型,也接受类中的方法。更优雅的解决方案是使用。或第三方库(如或)来解析提要 下面是一个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看起来不同,这就是为什么使用我提到的上述库之一是有意义的。我实际上使用的是simpleXML,但问题是描述标记中的任何嵌入HTML也会变成一个对象,这就是为什么我首先对其进行实体编码。然后,您的提要会被破坏。好的提要在CDATA中包装HTML和类似内容。如何更改模式以匹配所有嵌套节点的内容?谢谢