我堅持使用簡單的正則表達式來匹配內容中的網址。目標是從「/ 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>
請,提供了一個例子。你的任務聽起來很簡單,但我看不到任何要檢查的字符串 – gaussblurinc 2012-08-13 14:18:24
你可以使用一個正則表達式來做同樣的事情來檢查url是否以http和另一個正則表達式在php if語句內開始執行替代。編寫和理解起來更容易,而且一個複雜的單元可能不會更有效率。 – Vortexfive 2012-08-13 14:24:24