如何在 PHP 中使用正则表达式提取 HTML 内容
我知道,我知道...正则表达式不是提取 HTML 文本的最佳方法。但我需要从很多页面中提取文章文本,我可以将正则表达式存储在每个网站的数据库中。我不确定 XML 解析器如何与多个网站一起工作。您需要为每个网站提供单独的功能。
无论如何,我对正则表达式了解不多,所以请耐心等待。
我有一个格式与此类似的 HTML 页面,
<html>
<head>...</head>
<body>
<div class=nav>...</div><p id="someshit" />
<div class=body>....</div>
<div class=footer>...</div>
</body>
我需要提取主体类容器的内容。
我试过这个。
$pattern = "/<div class=\"body\">\(.*?\)<\/div>/sui"
$text = $htmlPageAsIs;
if (preg_match($pattern, $text, $matches))
echo "MATCHED!";
else
echo "Sorry gambooka, but your text is in another castle.";
我做错了什么?我的文字最终到达了另一座城堡。
*编辑:哦...没关系,我发现了 可读性代码
I know, i know... regex is not the best way to extract HTML text. But I need to extract article text from a lot of pages, I can store regexes in the database for each website. I'm not sure how XML parsers would work with multiple websites. You'd need a separate function for each website.
In any case, I don't know much about regexes, so bear with me.
I've got an HTML page in a format similar to this
<html>
<head>...</head>
<body>
<div class=nav>...</div><p id="someshit" />
<div class=body>....</div>
<div class=footer>...</div>
</body>
I need to extract the contents of the body class container.
I tried this.
$pattern = "/<div class=\"body\">\(.*?\)<\/div>/sui"
$text = $htmlPageAsIs;
if (preg_match($pattern, $text, $matches))
echo "MATCHED!";
else
echo "Sorry gambooka, but your text is in another castle.";
What am I doing wrong? My text ends up in another castle.
*EDIT: ooohh... never mind, I found readability's code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在匹配
class="body"
您的文档具有class=body
:您缺少引号。使用"/
(.*?)<\/div>/sui"
。You are matching for
class="body"
your document hasclass=body
: you're missing the quotes. Use"/<div class=\"?body\"?>(.*?)<\/div>/sui"
.