免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5452 | 回复: 3
打印 上一主题 下一主题

正则回调问题(处理xml内容中含有尖括号) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-05-12 17:44 |只看该作者 |倒序浏览
今天用PHP解析xml文档 大致如下内容:
<description>
<![CDATA[<a href='http://xx.com'>a link</a>]]>
</description>

用 simplexml_load_string无法读到description中间的内容,各位有什么高招?

我先说一下我的思路,尽管最终失败,算是抛砖引玉吧
第一步,我先讲上述字符串整理成如下形式:

<description>
<a href='http://xx.com>a link'></a>
</description>
第二步我打算将<a href='http://xx.com>a link'></a>部分的“<”和">"替换为&lt;或者&gt;形式;如下:

$str = preg_replace("/<description>(.*?)<\/description>/", search("$1"), $str);
function search($match){
$match = str_replace("<", "x", $match);
return $match;
}


但是我发现回调函数中str_replace函数无法执行;

各位可有什么思路或者解决办法,谢谢;

论坛徽章:
0
2 [报告]
发表于 2010-05-12 18:26 |只看该作者
你这个正则把所有的都匹配出来了,试试零宽断言

论坛徽章:
0
3 [报告]
发表于 2010-05-12 20:00 |只看该作者
xml格式错误了吧!

论坛徽章:
1
技术图书徽章
日期:2013-09-09 13:47:26
4 [报告]
发表于 2010-05-13 00:54 |只看该作者
本帖最后由 umyspl 于 2010-05-13 00:56 编辑

  1. <?php
  2. $str =<<<EOF
  3. <description>
  4. <![CDATA[<a href='http://xx.com'>a link</a>]]>
  5. </description>
  6. EOF;
  7. $str = preg_replace("/<description>((\n|\t|\r|.)*)<\/description>/ie", "search('\\1')", $str);
  8. echo $str;
  9. function search($match){
  10. $match = str_replace("<", "x", $match);
  11. return $match;
  12. }
  13. ?>
复制代码
结果:
---------- php ----------

x![CDATA[xa href='http://xx.com'>a linkx/a>]]>

Output completed (0 sec consumed)

你应该回家好好读读手册。
$str = preg_replace("/<description>((\n|\t|\r|.)*)<\/description>/ie", "search('\\1')", $str);


Example #4 Using the 'e' modifier

<?php
preg_replace("/(<\/?)(\w+)([^>]*>)/e",
             "'\\1'.strtoupper('\\2').'\\3'",
             $html_body);
?>
This would capitalize all HTML tags in the input text.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP