Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

How do I extract HTML content using Regex in PHP

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...