-1

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

Community
  • 1
  • 1
HyderA
  • 20,651
  • 42
  • 112
  • 180
  • 3
    Obviously, you haven't read SO's most upvoted answer, yet: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 . If you don't know much about regexes *and* about XML parsers, why start with regexes and not with the more useful approach of HTML parsing? – Boldewyn May 12 '10 at 12:09
  • Does that DIV contain any other sub-DIVs? – treznik May 12 '10 at 12:10
  • 1
    @Boldewyn, I did, i visualized that guy hunting me with a pitchfork while writing down this question. But I don't understand how i could scan multiple websites with XML parser. – HyderA May 12 '10 at 12:14
  • 1
    Well you could always store the XPath expressions. – Jakub Hampl May 12 '10 at 12:18
  • An interesting picture to imagine ;-) However, he *is* right, you will have a hard time unleashing regexes to arbitrary HTML. Even if it works with your test data, someone might insert a tag here or append an attribute there, and your craftfully tailored regex is paying its dept to nature. – Boldewyn May 12 '10 at 12:34
  • Use a HTML/XML parser and store a single XPath path per website. – Ignacio Vazquez-Abrams May 12 '10 at 12:17

1 Answers1

0

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

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106