Preg_replace覆盖

时间:2012-04-04 19:17:50

标签: php preg-replace

我在PHP中有一些preg_replace函数有点问题。 首先,我$message = preg_replace("/\[img\](.*?)\[\/img\]/is", '<img src="$1" alt="" />', $message);用图像替换[img] http://example.com/img.png [/ img]。但之后我还有一个preg_replace替换URL:

$message = preg_replace("/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", '<a href="$1">title[$1]</a>', $message);

是否可以防止<img src=''中的网址也替换为链接?就像在img preg_replace之前放置URL替换函数并更改模式一样,它不会更改BB-Code括号内的URL?

感谢您的回答!

2 个答案:

答案 0 :(得分:1)

怎么样?
$message = preg_replace("/(?i)\b[^\"]((?:htt ...

答案 1 :(得分:1)

更新:请阅读以下更新。

不确定。使用负面的lookbehind来检查背后的内容。

它的语法类似于:

(?x)
# Match abc if there is no ' or " behind
(?<!['"]) abc

有关详细信息,请参阅perlre


更新:

它似乎并没有真正起作用。这个技巧字面意思是后面没有'",所以regexp实际上看到的是这样的东西(匹配的字符串在<>中。

"http://<example.com/img>.png"

您应该阅读Ignore html tags in preg_replace而不是使用此技巧。有时regexp不是解决方案,而且是其中一种情况。