【问题标题】:Make links clickable with regex使用正则表达式使链接可点击
【发布时间】:2009-08-07 03:24:01
【问题描述】:

是否有一个正则表达式可以找到包含以 http:// 或 www 开头的单词并用 <a>$1</a> 包装的字符串?

一直在谷歌上搜索,但我似乎找不到终极版。

另一个问题,如果它在<img> 标签内,你能不能让它忽略它?

非常感谢!

【问题讨论】:

    标签: php regex


    【解决方案1】:
        $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);
    

    【讨论】:

    • 一个我经常使用的函数的sn-p;还包含(未显示)用链接替换电子邮件的代码,可以选择混淆
    【解决方案2】:

    祝你好运——找到起点相当容易(大多数时候);找到终点?祝你好运:

    • 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 允许这样做。

    【讨论】:

    • 使用字符串中的所有字符有什么问题?如果在使用 htmlentites 之类的功能逃避它们之前,一切都很好,不是吗?
    • @kwichz:问题是在计划文本字符串中,很容易找到 http://,但很难找到 URL 的 end,因为URL 中允许的所有字符。例如:He said to 'Try searching at http://www.google.com/.' 句点和单引号都是 URL 中的有效字符,因此程序很难看到该 URL 的结束位置。
    • 我看不到问题所在。只需匹配,直到找到第一个空格,它在大多数情况下都可以工作。
    • @MaciejSwic Well, that fails on the common convention of wrapping URLs in punctuation (e.g., &lt;http://www.example.com&gt;). 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搞砸......)
    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多