如何在PHP中使用Regex提取HTML内容 [英] How do I extract HTML content using Regex in PHP

查看:208
本文介绍了如何在PHP中使用Regex提取HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,我知道...正则表达式不是提取HTML文本的最佳方法。但我需要从很多页面中提取文章文本,我可以在每个网站的数据库中存储正则表达式。我不确定XML解析器如何与多个网站一起工作。每个网站都需要一个单独的功能。



在任何情况下,我对正则表达式都不太了解,请耐心等待。



我有一个类似于此格式的HTML页面

 < html> 
< head> ...< / head>
< body>
< div class = nav> ...< / div>< p id =someshit/>
< div class = body> ....< / div>
< div class = footer> ...< / div>
< / body>

我需要提取body类容器的内容。



我试过了。

  $ pattern =/< div class = \body \ > \(。*?\)< \ / div> / sui
$ text = $ htmlPageAsIs;
if(preg_match($ pattern,$ text,$ matches))
echoMATCHED!;
else
回声对不起gambooka,但你的文字在另一座城堡。;

我做错了什么?我的文本最终在另一座城堡。



*编辑:ooohh ...没关系,我发现可读性的代码

解决方案

<您正在匹配 class =body您的文档有 class = body :您错过了引号。使用/< div class = \?body \?>>(。*?)< \ / div> / sui p>

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

解决方案

You are matching for class="body" your document has class=body: you're missing the quotes. Use "/<div class=\"?body\"?>(.*?)<\/div>/sui".

这篇关于如何在PHP中使用Regex提取HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆