EnexoOnoma
EnexoOnoma

Reputation: 8836

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 $paragraph;
echo "<br>";
}
?> 

Thank you!

Upvotes: 1

Views: 1122

Answers (2)

Legy
Legy

Reputation: 411

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;
}

Upvotes: 0

CanSpice
CanSpice

Reputation: 35790

Don't use a regex to parse HTML. Use a DOM parser like DOMDocument instead.

Upvotes: 1

Related Questions