Reliably parsing HTML elements using RegEx [duplic

2019-09-25 10:18发布

问题:

Possible Duplicate:
Best methods to parse HTML with PHP

I'm trying to parse a webpage using RegEx, and I'm having some trouble making it work in a reliable manner.

Say I wanted to parse the code that creates a div element, and I want to extract everything between <div> and </div>. Now, this code could just be <div></div>, but it could also very well be something like:

<div class="thisIsMyDivClass"><p>This text is inside the div</p></div>

How can I make sure that no matter how many characters that are in between the greater-than/less-than signs of the initial div tag and the corresponding last div tag, I'll always only get the content in between them? If I specify that the number of characters following < can be anything from one to ten thousand, I will always be extracting the > after ten thousand characters, and thus (most likely, unless there is a lot of code or text in between) retrieve a bunch of code in between that I don't need.

This is my code so far (not reliable for the aforementioned reason):

/<.{1,10000}>/

回答1:

Regular expressions describe so called regular languages - or Type 3 in the Chomsky hierarchy. On the other hand HTML is a context free language which is Type 2 in the Chomsky hierarchy. So: There is no way to reliably parse HTML with regular expressions in general. Use a HTML parser instead. For PHP you can find some suggestions in this question: How do you parse and process HTML/XML in PHP?



回答2:

You will need a Lexical analyser and grammar checker to parse html correctly. RegEx main focus was for searching strings for patterns.



回答3:

I would suggest using something like DOM. I am doing a large scale site with and using DOM like crazy on it. It works, works good, and with a little work can be extremely powerful.

http://php.net/manual/en/book.dom.php