How to retrieve content of a DIV using regex? [duplicate]
Possible Duplicates:
Xpath not behaving for me in parsing basic h开发者_开发技巧tml
I know how to get content from a div with static name (i.e. always the same in the whole page). However, my case is "post_id_xxxxx", something like this:
<div id="post_id_12345">abc</div>
<div id="post_id_67890">abc</div>
<div id="post_id_31234">abc</div>
I would like to extract the "abc" string, but seems difficult to me since every div has different ID.
Thanks.
This is still workable with a regex, if it's really only about the overly simplistic cases in your example:
preg_match('#<div\s[^>]*id="post_id_12345"[^>]*>(.*?)</div>#', $str, $m)
But as soon as you have nested divs in the document or other complex constructs, you need to use a HTML parser. To give you a real example instead of generic links, use phpQuery or QueryPath with:
print qp($html)->find("#post_id_12345")->text();
Do not parse HTML/XML with regexp. HTML has a structure that a html specific parser can exploit. See this classic link: RegEx match open tags except XHTML self-contained tags
You should try some of PHPs parsers like domdocument
DO NOT USE THIS
Here is a regexp that will match the example you specified. It will not work on more complicated structures (e.g. nested divs). You haven't really specified what invariants you know about the structure of your html, from the example this should work. You can expand this regexp to match more complexities, but a real parser will be much more robust and easier.
<div id="post_id_[0-9]{5}">(.*)</div>
精彩评论