I wish to retrieve data between <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#EBEBEB">
and </table>
using Php.Can any one please specify me the corr开发者_StackOverflow社区ect regular expression for retrieving data between the given table tags
I believe what you need is XPath rather than Regular Expressions.
It depends on what you're retrieving. I'm no PHP pro myself, but here's how I would go about it:
<?php
$contents = file_get_contents($_SERVER['PHP_SELF']);
$array = explode("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#EBEBEB\">", $contents);
$newarray = explode("</table>", $array[1]);
$yourdata = $newarray[0];
?>
You should use this method if you don't mind having the rest of the raw HTML in there. Otherwise, someone else might have a better solution.
While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.
What I recommend you do is use a DOM parser such as phpQuery
and use it as such:
function get_first_image($html){
$dom = phpQuery::newDocument($html);
$first_img = $dom->find('img:first');
if($first_img !== null) {
return $first_img->attr('src');
}
return null;
}
Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.
A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the alt
attribute to be after the src
or the opposite, and to overcome this limitation would add more complexity to the regular expression.
Also, consider the following. To properly match an <img>
tag using regular expressions and to get only the src
attribute (captured in group 2), you need the following regular expression:
<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>
And then again, the above can fail if:
- The attribute or tag name is in capital and the
i
modifier is not used. - Quotes are not used around the
src
attribute. - Another attribute then
src
uses the>
character somewhere in their value. - Some other reason I have not foreseen.
So again, simply don't use regular expressions to parse a dom document.
精彩评论