2011-06-27 36 views
0

我想用正則表達式將鏈接轉換爲頁面錨點。我對正則表達式很陌生,我試過學習。正則表達式鏈接到頁面錨點

我已經使用php字符串替換爲根網址,但需要使用preg_replace來更改/而不是當/是諸如<//>之類的html標記的一部分時。

$string = '<ul> 
<li><a href="http://www.somedomain.com/something/somethingelse">Hello World</a></li> 
<li><a href="http://www.somedomain.com/something/somethingelse">Hello World</a></li> 
</ul>'; 

// Replace root url with # 
$string = str_replace('http://www.somedomain.com/', '#' , $string); 

// This replaces the/with hyphens, but I need it to not do this if is preceeded or followed by <or> 
$string = preg_replace("/\//", "-", $string); 
echo $string; 

回答

1

種類:

preg_replace('/([^<]|^)\/([^>]|$)/', '$1-$2', $string); 

但整個任務看起來並不像解決原始任務的可靠方法。

+0

感謝您的回覆,雖然我不確定它是幹什麼的?我想替換/從一個字符串,但不是如果它是 Jason

+0

對不起,有一系列的錯誤。我不知道我爲什麼寫這個 - 也許我太累了。現在它已經過修復和測試。 –

+1

此外,正則表達式可以簡化,如果你不需要整個字符串邊緣的斜槓:'/([^ <])\/([^>])/ s' –