排除 link 以 PREG_REPLACE 中的字符开头

Exclude link starts with a character from PREG_REPLACE

此代码将任何 url 转换为可点击的 link:

$str = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href=""></a>', $str);

如何让url以[字符开头时不转换?像这样:

[http://google.com

使用 negative lookbehind:

$str = preg_replace('/(?<!\[)(http[s]?:\/\/[^\s]*)/i', '<a href=""></a>', $str);
                      ^^^^^^^

那么,以[开头的http...子串将不会被匹配。

您可以将图案增强为

preg_replace('/(?<!\[)https?:\/\/\S*/i', '<a href="[=11=]">[=11=]</a>', $str);

即:删除 ()(捕获组)并在替换模式中用 [=17=] 替换 </code> 的反向引用,并注意<code>[^\s] = \S,但更短。另外,[s]? = s?.