我坚持使用简单的正则表达式来匹配内容中的网址。目标是从“/ 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