查找字符串中的所有链接,并使用PHP将它们转换为锚标记

时间:2009-12-08 04:40:16

标签: php regex

http://stackoverflow.com

应该成为

<a href="http://stackoverflow.com">http://stackoverflow.com</a>

左编辑:如果原始字符串中的锚标记保持不变,那就太棒了。

1 个答案:

答案 0 :(得分:2)

John Gruber刚刚发布了一个有趣的正则表达式示例来捕获URL: Daring Fireball regex to get URLs

为了减少追逐,他选择的(自由主义,长期)模式是:

\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))

这可以捕获以下所有内容:

http://foo.com/blah_blah
http://foo.com/blah_blah/
(Something like http://foo.com/blah_blah)
http://foo.com/blah_blah_(wikipedia)
(Something like http://foo.com/blah_blah_(wikipedia))
http://foo.com/blah_blah.
http://foo.com/blah_blah/.
<http://foo.com/blah_blah>
<http://foo.com/blah_blah/>
http://foo.com/blah_blah,
http://www.example.com/wpstyle/?p=364.
http://✪df.ws/123
rdar://1234
rdar:/1234
http://userid:password@example.com:8080
http://userid@example.com
http://userid@example.com:8080
http://userid:password@example.com
http://example.com:8080 x-yojimbo-item://6303E4C1-xxxx-45A6-AB9D-3A908F59AE0E
message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e
http://➡.ws/䨹
www.➡.ws/䨹
<tag>http://example.com</tag>
Just a www.example.com link.

所以你要用preg_filter这样的模式,然后以某种方式迭代返回的匹配数组。我猜。我讨厌正则表达式。