Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中替换a href链接_Php_Html - Fatal编程技术网

如何在php中替换a href链接

如何在php中替换a href链接,php,html,Php,Html,我需要替换所有,如何提取字符串' 请帮助我。使用DOMDocument $dom = new DOMDocument; $dom->loadHTML($html); foreach ($dom->getElementsByTagName('a') as $node) { //Do your processing here } 好的,既然没有关于如何操作DOM的明确答案,我认为,您想要操作它: $foo = '<body><p> Some BS and

我需要替换所有
,如何提取字符串
'

请帮助我。

使用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...
$foo='一些BS和

'; $dom=新的DOMDocument; $dom->loadHTML($foo)//在这里解析DOM $links=$dom->getElementsByTagName('a')//获取所有链接 foreach($links作为$link) {//$links是DOMNodeList实例,$link是DOMNode实例 $replaceText=$link->nodeValue.:'。$link->getAttribute('href');//内部文本:href属性 $replaceNode=$dom->createTextNode($replaceText);//创建一个DOMText实例 $link->parentNode->replaceChild($replaceNode,$link);//用DOMText实例替换链接 } echo$dom->saveHTML()//编辑后回显HTML。。。
这表明:

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

一些B和链接!:https://www.google.com

从阅读手册开始,点击这里使用的所有方法(和相关类)。DOMDocument API,就像客户端JS中的DOM API一样,体积庞大,并没有那么直观,但事实就是如此…

可以使用
saveXML
方法和/或。。。总之,使用这些代码和提供的链接,到达您想要的位置应该不会太困难。

只需解析DOM就可以了…使用-其他一切都是废话,真的。如果有少量静态链接要替换,请使用替换。如果更复杂,则解析DOM。
<!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>