如何替换php中的a href链接


How to replace a href links in php

我需要用php文件中的一些文本替换所有<a> href。我用过

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

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

请帮帮我。

使用DOMDocument。

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

好吧,由于没有明确的答案来说明如何操作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>

首先阅读DOMDocument手册,然后点击我在这里使用的所有方法(和相关类)。DOMDocument API,就像客户端JS中的DOM API一样,体积庞大,并不那么直观,但它就是这样…
在没有doctype的情况下,可以使用saveXML方法和/或一些字符串操作来响应实际的html。。。总而言之,使用这些代码和提供的链接,到达您想要的位置应该不会太困难。