[英]Replace anchor text with PHP (and regular expression)
我有一個包含很多鏈接的字符串,在將它們打印到屏幕上之前,我想對其進行調整:
我有類似以下內容:
<a href="http://www.dont_replace_this.com">replace_this</a>
並希望最終得到這樣的結果
<a href="http://www.dont_replace_this.com">replace this</a>
通常我只會使用類似的東西:
echo str_replace("_"," ",$url);
在這種情況下,我無法執行此操作,因為URL包含下划線,因此斷開了我的鏈接,以為我可以使用正則表達式來解決此問題。
有任何想法嗎?
這是正則表達式: <a(.+?)>.+?<\\/a>
。
我正在做的是將重要的動態內容保留在anchor標簽中,並用以下功能替換:
preg_replace('/<a(.+?)>.+?<\/a>/i',"<a$1>REPLACE</a>",$url);
這將涵蓋大多數情況,但我建議您進行檢查以確保沒有遺漏或更改任何意外情況。
pattern = "/_(?=[^>]*<)/";
preg_replace($pattern,"",$url);
您可以使用此正則表達式
(>(.*)<\s*/)
編輯:
$replaced_text = preg_replace_callback('~(>(.*)<\s*/)~g','uscore_replace', $text);
function uscore_replace($matches){
return str_replace('_','',$matches[1]); //try this with 1 as index if it fails try 0, I am not entirely sure
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.