2013-08-23 77 views
0

我需要用php文件中的一些文本替换所有<a> hrefs。我已经使用如何在php中替换href链接

preg_replace('#\s?<a.*/a>#', 'text', $string); 

但是这会替换所有具有相同文本的链接。每个链接都需要不同的文字。 如何做到这一点。也有可能完全获得href链接,意味着如果我有一个包含链接<a href="www.google.com">Google</a>的文件,我如何提取字符串'<a href="www.google.com">Google</a>'

请帮帮我。

+2

只是解析DOM已经... –

+0

使用http://php.net/domdocument - 其他一切都是废话,真的。如果您想要替换一些静态链接,请使用strireplace。如果更复杂,则解析DOM。 – DanFromGermany

回答

1

使用DOMDocument。

$dom = new DOMDocument; 
$dom->loadHTML($html); 
foreach ($dom->getElementsByTagName('a') as $node) { 
    //Do your processing here 
} 
0

OK,因为有一个关于如何操作DOM的方式没有明确的答案,我想,你需要处理它:

$foo = '<body><p> Some BS and <a href="https://www.google.com"> Link!</a></p></body>'; 
$dom = new DOMDocument; 
$dom->loadHTML($foo);//parse the DOM here 
$links = $dom->getElementsByTagName('a');//get all links 
foreach($links as $link) 
{//$links is DOMNodeList instance, $link is DOMNode instance 
    $replaceText = $link->nodeValue.': '.$link->getAttribute('href');//inner text: href attribute 
    $replaceNode = $dom->createTextNode($replaceText);//create a DOMText instance 
    $link->parentNode->replaceChild($replaceNode, $link);//replace the link with the DOMText instance 
} 
echo $dom->saveHTML();//echo the HTML after edits... 

此推出:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body><p> Some BS and Link!: https://www.google.com</p></body></html> 

刚开始阅读the DOMDocument手册,并点击我在这里使用的所有方法(和相关类)。 DOMDocument API,就像客户端JS中的DOM API一样笨重,并不那么直观,但这就是它的样子......
回应实际的html,没有doctype可以使用saveXML方法完成,并且/或some string operations ...总而言之,使用此代码作为基础和提供的链接不应该太难以达到您想要的位置。