【发布时间】:2009-08-07 03:24:01
【问题描述】:
是否有一个正则表达式可以找到包含以 http:// 或 www 开头的单词并用 <a>$1</a> 包装的字符串?
一直在谷歌上搜索,但我似乎找不到终极版。
另一个问题,如果它在<img> 标签内,你能不能让它忽略它?
非常感谢!
【问题讨论】:
是否有一个正则表达式可以找到包含以 http:// 或 www 开头的单词并用 <a>$1</a> 包装的字符串?
一直在谷歌上搜索,但我似乎找不到终极版。
另一个问题,如果它在<img> 标签内,你能不能让它忽略它?
非常感谢!
【问题讨论】:
$text = trim($text);
while ($text != stripslashes($text)) { $text = stripslashes($text); }
$text = strip_tags($text,"<b><i><u>");
$text = preg_replace("/(?<!http:\/\/)www\./","http://www.",$text);
$text = preg_replace( "/((http|ftp)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\" target=\"_blank\">\\0</a>",$text);
【讨论】:
祝你好运——找到起点相当容易(大多数时候);找到终点?祝你好运:
http://example.com/bob.jones.4.http://example.com/bob.jones.4?http://example.com/bob.jones.4!http://stackoverflow.com/questions/1242733/make-links(oh-noes)http://example.com/bob.'magic'.jones*2!http://example.com/~(*)!这些是有效的 URL。请参阅 RFC2396。但有时你想要尾随标点符号,有时你不需要。
/me 想知道他可以使用带有 (*')! 的 url 做什么,现在他知道 RFC2396 允许这样做。
【讨论】:
He said to 'Try searching at http://www.google.com/.' 句点和单引号都是 URL 中的有效字符,因此程序很难看到该 URL 的结束位置。
Well, that fails on the common convention of wrapping URLs in punctuation (e.g., <http://www.example.com>). Or on URLs at ends of sentences, like http://www.example.com/page1.html. You can get a 90% solution, as you say, but should be aware of how it'll fail. (用`包裹评论以防止SO搞砸......)