[英]replace all links in text by Regular Expressions
我想替換文本中的所有鏈接除了圖像鏈接
$text = '<p>
<a href="http://msn.com" rel="attachment wp-att-7046"><img class="alignnone size-full wp-image-7046" alt="geak-eye-mars" src="http://google/2013/06/geak-eye-mars.jpg" width="619" height="414" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>';
我想要替換(http://msn.com and http://google.com)
和其他鏈接,但這樣的圖像鏈接(http://google/2013/06/geak-eye-mars.jpg)
仍然存在因為它..我希望你理解我..我只想替換這個標簽之間的所有鏈接
href="Link"
通過此代碼
$text = ereg_replace("all links","another link">",$text);
謝謝
使用DOM執行此操作:
$text = <<<LOD
<p><a href="http://msn.com" rel="attachment wp-att-7046">
<img src="http://google/2013/06/geak-eye-mars.jpg" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>
LOD;
$doc = new DOMDocument();
@$doc->loadHTML($text);
$aNodes = $doc->getElementsByTagName("a");
foreach($aNodes as $aNode) {
$href = $aNode->getAttribute("href");
$new_href = '!!!Youhou!!! '. $href;
$aNode->setAttribute("href", $new_href);
}
$new_text = $doc->saveHTML();
如果您想要一個不會破壞的永久解決方案,請使用DOM解析器,就像其他答案所示。 使用正則表達式來解析html是一個非常糟糕的主意。
但是,如果您只想要一次性的快速解決方案,那么這樣的事情就會:
preg_replace('/(href=["\']?)[^"\']+/', '$1' . $newtext, $html);
保證,這將在某些html文件上失敗(例如,如果URL沒有包含在引號中),但只要編寫html文件的人使用最佳實踐,它就可以使用。 不要在生產代碼中使用它。 永遠。
$text = <<<LOD
<p><a href="http://msn.com" rel="attachment wp-att-7046">
<img src="http://google/2013/06/geak-eye-mars.jpg" /></a></p>
bla bla bla bla bla bla
<p><a href="http://google.com" target="_blank">any word</a>
bla bla bla bla bla bla
</p>
LOD;
$doc = new DOMDocument();
$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
@$doc->loadHTML($text);
$aNodes = $doc->getElementsByTagName("a");
foreach($aNodes as $aNode) {
$href = $aNode->getAttribute("href");
$new_href = '!!!Youhou!!! '. $href;
$aNode->setAttribute("href", $new_href);
}
$new_text = $doc->saveHTML();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.