2012-08-13 120 views
1

我堅持使用簡單的正則表達式來匹配內容中的網址。目標是從「/ folder/id/123」之類的鏈接中刪除該文件夾,並將其替換爲「id/123」,因此它是相同文件夾中相對較短的文件夾。正則表達式:否定斷言

我其實

$pattern = "/\/?(\w+)\/id\/(\d)/i" 
$replacement = "id/$2"; 
return preg_replace($pattern, $replacement, $text); 

,似乎很好地工作。

但是,我想要測試每個匹配的url不包含http://,如果它是一個外部網站,它也使用相同的模式/文件夾/ ID/123。

我試過/ [^ http://]或(?<!html)...和不同的事情沒有成功。任何幫助將是很好的:-)

$pattern = "/(?<!http)\b\/?(\w+)\/id\/(\d)/i"; ??????? 

謝謝!

下面是一些例子:非常感謝你的幫助:-)

(these should be replaced, "same folder" => short relative path only) 
<a href="/mysite_admin/id/414">label</a> ==> <a href="id/414">label</a> 
<a href="/mYsITe_ADMIN/iD/29">label with UPPERCASE</a> ==> <a href="id/414">label with UPPERCASE</a> 

(these should not be replaced, when there is http:// => external site, nothing to to) 
<a href="http://mysite_admin/id/414">label</a> ==> <a href="http://mysite_admin/id/414">label</a> 
<a href="http://www.google_admin.com">label</a> ==> <a href="http://www.google_admin.com">label</a> 
<a href="http://anotherwebsite.com/id/32131">label</a> ==> <a href="http://anotherwebsite.com/id/32131">labelid/32131</a> 
<a href="http://anotherwebsite_admin.com/id/32131">label</a> ==> <a href="http://anotherwebsite_admin.com/id/32131">label</a> 
+0

請,提供了一個例子。你的任務聽起來很簡單,但我看不到任何要檢查的字符串 – gaussblurinc 2012-08-13 14:18:24

+0

你可以使用一個正則表達式來做同樣的事情來檢查url是否以http和另一個正則表達式在php if語句內開始執行替代。編寫和理解起來更容易,而且一個複雜的單元可能不會更有效率。 – Vortexfive 2012-08-13 14:24:24

回答

1

無需爲<,這是用來標記look-back斷言,只要用/^(?!http)\/?(\w+)\/node\/(\d)/i作爲一個模式,它匹配/富/酒吧/ 123,但不http://www.google.com/foo/bar/123

this question提供了一個很好的概述,可以幫助您與此

+0

好吧,現在感謝與http的鏈接不再匹配。太好了! Mhhh終於看起來什麼都沒有匹配: - /我沒有更多的替代品。非常感謝我會嘗試從您提供的鏈接中學習。 – 2012-08-13 14:00:37

+0

好吧,'echo preg_replace('/ ^(?! http)\ /?(\ w +)\/node \ /(\ d)/ i','id/$ 2','foo/node/123'); 'echo'id/123'對我來說。你可以在[這裏](http://www.functions-online.com/preg_replace.html)中進行測試,直到這種模式適合你。另外,我不喜歡這樣做,但如果答案有幫助或解決了您的問題,那麼習慣於upvote或接受它;-) – 2012-08-13 14:18:12

0

從細PHP手冊 - Assertions

注意,顯然類似的模式欄沒有找到一個 發生「欄」由比「富」以外的東西前面的;(富?!)它 發現任何「bar」的出現,因爲當接下來的三個字符是「bar」時,斷言 (?!foo)總是TRUE。爲了達到這種效果,需要使用向後看斷言。

如:

$pattern = "/(?<!http:\/)\/(\w+)\/id\/(\d)/i";