Get the contents of a tag using preg match all
how can I get the link of this string using preg match all ?
<h3 class='post-title entry-title'>
<a href='http://domain.blogspot.com/2011/03/blog-post_111.html'>Test Post</a>
</h3>
This is what I did so far
<?php
$string = file_get_contents('http://www.domain.com');
$regex_pattern = "/<h3 class=\'post-title entry-title\'>([^`]*?)<\/h3>/";
unset($matches);
preg_match_all($regex_pattern, $string, $matches);
foreach ($matches[0] as $paragraph) {
echo $par开发者_Python百科agraph;
echo "<br>";
}
?>
Thank you!
Don't use a regex to parse HTML. Use a DOM parser like DOMDocument instead.
maybe /href='([^']*)'/gi
helps?
when creating Regular Expressions RegExr is a nice tool. But regular expressions are far to slow. you can get the same effect with a bit more code and the 3 functions: strlen, strpos and substr. That would be one of the fastes versions how to handle this.
Try
function between ( $before , $after , $subject )
{
$subject = $subject;
$start = strpos ( $subject , $before );
if ( $start !== false )
{
$end = strpos ( $subject , $after , $start );
if ( $end !== false )
{
return substr ( $subject , $start + strlen ( $before ) , $end - ( $start + strlen ( $before ) ) );
};
};
return false;
}
精彩评论