加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP:使用带有htmlentities的preg_replace

发布时间:2020-12-13 21:33:53 所属栏目:PHP教程 来源:网络整理
导读:我正在写一个RSS到 JSON解析器,作为其中的一部分,我需要在description标签内找到的任何标签上使用htmlentities().目前,我正在尝试使用preg_replace(),但我正在努力使用它.我当前的(非工作)代码如下所示: $pattern[0] = "/description(.*?)/description
我正在写一个RSS到 JSON解析器,作为其中的一部分,我需要在description标签内找到的任何标签上使用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);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读