0

I have a string with some HTML. In the HTML is a list of anchors (<a> tags) and I would like to get the last of those anchors.

<div id="breadcrumbs">
    <a href="/">Home</a>
    <a href="/suppliers">Suppliers</a>
    <a href="/suppliers/jewellers">This One i needed</a>  
    <span class="currentpage">Amrapali</span>
</div>
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Harman
  • 539
  • 5
  • 16

3 Answers3

4

Make use of DOMDocument Class.

<?php
$html='<div id="breadcrumbs">
    <a href="/">Home</a>
    <a href="/suppliers">Suppliers</a>
    <a href="/suppliers/jewellers">This One i needed</a>
    <span class="currentpage">Amrapali</span>
</div>';
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $tag) {
   $arr[]=$tag->nodeValue;
}
echo $yourval = array_pop($arr); //"prints" This One i needed
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
2

You should look for the next a tags with a negative lookahead:

(?s)<a(?!.*<a).+</a>

and the code:

preg_match("#(?s)<a(?!.*<a).+</a>#", $html, $result);
print_r($result);

Output:

Array
(
    [0] => <a href="/suppliers/jewellers">This One i needed</a>
)

Regex demo | PHP demo

revo
  • 47,783
  • 14
  • 74
  • 117
0

Try this

<?php

$string = '<div id="breadcrumbs">
<a href="/">Home</a>
<a href="/suppliers">Suppliers</a>
<a href="/suppliers/jewellers">This One i needed</a>  
<span class="currentpage">Amrapali</span>
</div>';


//$matches[0] will have all the <a> tags
preg_match_all("/<a.+>.+<\/a>/i", $string, $matches);


//Now we remove the <a> tags and store the tag content into an array called $result
foreach($matches[0] as $key => $value){

    $find = array("/<a\shref=\".+\">/", "/<\/a>/");
    $replace = array("", "");

    $result[] = preg_replace($find, $replace, $value);
}


//Make the last item in the $result array become the first
$result = array_reverse($result);

$last_item = $result[0];

echo $last_item;


?>
Adlin Ling
  • 382
  • 1
  • 7