从2字符串得到独特的ahref?

时间:2015-05-25 09:56:37

标签: php string

在我的页面中,我有两个这样的字符串:

$post_des = 'this is an <a href = "http://example.com/test"> example </a> string '; 

$post_detail = 'this is a new <a href = "http://example.com/test"> example </a> string ' ;

我想在我的页面中删除所有重复的ahref。有谁能给我一个解决方案? 我想这样:

$post_des = 'this is an <a href = "http://example.com/test"> example </a> string '; 

$post_detail = "this is a new example string " ;

1 个答案:

答案 0 :(得分:1)

您可以使用DomDocument Class,例如:

$html = '<a href="http://www.google.com">Google</a><a href="http://www.google.com">Google</a><a href="http://www.yahoo.com">Google</a>';

$dom = new DomDocument();
$dom->loadHtml($html);

$anchors = $dom->getElementsByTagName('a');

foreach($anchors as $anchor){
    //Check each anchor href attribute
    if($anchor->getAttribute('href') == 'http://www.google.com'){
        $anchor->setAttribute('href','http://example.com');
    }
}
echo $dom->saveHTML();

希望它会对你有所帮助。