2012-08-13 117 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";