开发者

Reliably parsing HTML elements using RegEx [duplicate]

开发者 https://www.devze.com 2023-03-20 08:24 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Best methods to parse HTML with PHP
This question already has answers here: Closed 11 years ago.

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&g开发者_Python百科t;, 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}>/


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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消