2012-02-02 25 views
2

我有一些文本包含html標記,我想用其他替換所有的鏈接,但我想只替換本地鏈接,而不是以http:// 爲例:如何使用preg_replace替換排除的模式

<a href="local_link">test link</a> 
    ==> <a href="local_link_to_be_replace?url=local_link">test link</a> 
<a href="http://www.youtube.com">Video</a> 
    ==> <a href="http://www.youtube.com">Video</a> 

我試試這個preg_replace函數,但不工作:

$exclude = '<a href=\"http://.*?'; 
$pattern = '<a href=\".*?'; 
$content=preg_replace("~(($exclude)?($pattern))~i",'<a href="/action.php?url=$4',$content); 

謝謝!

+1

一個小提示:你引用的第四子模式'$ 4'在更換模式,但實際上,因爲你打開三個托架只有3個。 – tim 2012-02-02 09:32:50

回答

2

什麼是這樣的:

$content = preg_replace('#<a href="([^:]*)">#i', '<a href="/action.php?url=$1">', $content); 
+0

感謝他的工作:) – 2012-02-02 09:52:11