繁体   English   中英

如何在php中替换href链接

[英]How to replace a href links in php

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

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一样,体积庞大而且不那么直观,但这就是它的方式......
回应实际的html,没有doctype可以使用saveXML方法和/或一些字符串操作来完成 ...总而言之,使用这段代码作为基础,到达你想要的地方应该不会太难,和提供的链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM