簡體   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