获取最后一个元素(<a>) tag content from html</a>

时间:2014-01-04 18:52:39

标签: php regex preg-match

我有一些带有HTML的字符串。在HTML中是一个锚点列表(<a>标签),我想得到最后一个锚点。

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

3 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:2)

您应该查找具有否定前瞻的下一个a代码:

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

和代码:

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

<强>输出

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

Regex demo | PHP demo

答案 2 :(得分:0)

试试这个

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


?>