preg_match - 替换未被引号括起的网址

时间:2013-08-06 17:46:45

标签: regex preg-replace

我需要在某些尚未链接的内容中添加指向网址的链接。这个内容来自Joomla内部的许多地方,有时它是html,有时它是文本。我需要一个单行的正则表达式来执行此操作。

考虑内容:

some text then url: <a href="http://j25.localhost/something">Link</a> and some
other text<br />url:http://j25.localhost/something2 and some other text...

我的正则表达式是:

$content = preg_replace('@(?:[^"])(https?://?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@i', '<a href="$1">$1</a>', $content);

并且它几乎可以工作(它跳过第一个并匹配第二个)但是在第二个它包含“http ....”之前的字符“:”并且在替换之后我的“:”消失了in:“<br />url<a ...”而不是“<br />url:<a ...

该怎么办?

1 个答案:

答案 0 :(得分:0)

使用以下代码更改您的代码:

$content = preg_replace(
  '@(^|[^"])(https?://?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@i',
  '$1<a href="$2">$2</a>', $content);

这将捕获http://之前的字符并将其放在输出文本中。

虽然我必须提醒你,正则表达式不是解析HTML文本的可靠方法。