Reputation: 5288
I have a bunch of strings that may or may not have a substring similar to the following:
<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>
Im trying to retrieve the '5' at the end of the link (that isnt necessarily a one digit number, it can be huge). But, this string will vary. The text before the link, and after, will always be different. The only thing that will be the same is the <a class="tag" href="http://www.yahoo.com/
and the closing </a>
.
Upvotes: 0
Views: 159
Reputation: 23580
I would got with "basename":
// prints passwd
print basename("/etc/passwd")
And to get the link you could use:
$xml = simplexml_load_string( '<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>' );
$attr = $xml->attributes();
print $attr['href'];
And finally: If you don't know the whole structure of the string, use this:
$dom = new DOMDocument;
$dom->loadHTML( '<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>asasasa<a class="tag" href="http://www.yahoo.com/6"> blah blah ...</a>' );
$nodes = $dom->getElementsByTagName('a');
foreach ($nodes as $node) {
print $node->getAttribute('href');
print basename( $node->getAttribute('href') );
}
As this will also fix invalid HTML code.
Upvotes: 0
Reputation: 197775
As you only need to retrieve the 5, it's pretty straight forward:
$r = pret_match_all('~\/(\d+)"~', $subject, $matches);
It's then in the first matching group.
If you need more information like the link text, I would suggest you to use a HTML Parser for that:
require('Net/URL2.php');
$doc = new DOMDocument();
$doc->loadHTML('<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>');
foreach ($doc->getElementsByTagName('a') as $link)
{
$url = new Net_URL2($link->getAttribute('href'));
if ($url->getHost() === 'www.yahoo.com') {
$path = $url->getPath();
printf("%s (from %s)\n", basename($path), $url);
}
}
Example Output:
5 (from http://www.yahoo.com/5)
Upvotes: 0
Reputation: 5258
You can do it using preg_match_all
and <a class="tag" href="http:\/\/(.*)\/(\d+)">
regular expression.
Upvotes: 1