请教 preg_replace() 过滤 html 标签

2016-09-19 10:32:26 +08:00
 lissome

文章正文中有大量 html 标签,类似这样的:

<h1>标题</h1>
<p>文字文字</p>
<img xxxx />

需要从文章正文提取摘要,现在用的办法是先过滤掉 html 标签,然后截取前 n 个字

$patterns = ['/<.+>/', '/&nbsp;/'];
$replacements = ['', ''];

$text = preg_replace($patterns, $replacements, $html);

但是替换结果是一个空字符串,是匹配了第一个 < 和最后一个 > ?

请问正则应该怎么写?

或者有没有其它方法从正文提取摘要?

2257 次点击
所在节点    PHP
4 条回复
fahai
2016-09-19 10:42:25 +08:00
可以把<.+>改成<.*?>或者使用 strip_tags
lissome
2016-09-19 10:43:10 +08:00
strip_tags
http://php.net/manual/en/function.strip-tags.php

刚刚我也查到了,谢谢!
@fahai
Herobs
2016-09-19 10:46:17 +08:00
- 取消贪婪匹配。
- 替换 &nbsp; 不要用正则表达式。
- 直接用现成的 strip_tags 。
gouchaoer
2016-09-20 23:53:16 +08:00
用 dom 库做这个啊

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/307174

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX