V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
liuyao729
V2EX  ›  程序员

求一段正则 链接

  •  
  •   liuyao729 · 2013-01-16 11:01:11 +08:00 · 3160 次点击
    这是一个创建于 4124 天前的主题,其中的信息可能已经有所发展或是发生改变。
    把 字符串中没有加链接的 url 加上链接 有的就不用了。
    $str = '<a href="xxxx">xsx</a> http://www.v2ex.com ';
    显示成
    <a href="xxxx">xsx</a> <a href="http://www.v2ex.com">http://www.v2ex.com</a>
    9 条回复    1970-01-01 08:00:00 +08:00
    jeffrey
        1
    jeffrey  
       2013-01-16 13:03:25 +08:00
    mozillazg
        2
    mozillazg  
       2013-01-16 13:40:11 +08:00   ❤️ 1
    个人觉得求正则的话,提问者应该至少说明三件事:
    * 使用的程序语言或工具
    * 待处理字符串特征及示例
    * 结果字符串的细节约束
    上面几点不讲清楚的话,回答者会搞不清楚提问者的具体需求,提问者也得不到想要的正则。
    mozillazg
        3
    mozillazg  
       2013-01-16 13:45:31 +08:00
    [^"']https?://\S+
    clowwindy
        4
    clowwindy  
       2013-01-16 13:57:02 +08:00   ❤️ 1
    liuyao729
        5
    liuyao729  
    OP
       2013-01-17 06:49:14 +08:00
    mozillazg
        6
    mozillazg  
       2013-01-17 09:11:13 +08:00
    @liuyao729 首先声明,我不会 PHP 也没有测试环境,只是上网查了一下 PHP 的替换函数。
    用了一个在线执行 PHP 代码的网站进行的测试(PHP5),
    该正则比较简陋并且对 <a href="http://xx?q=http://"></a> 会误判:
    $text = 'http://abc<a href="http://xxx">xsx</a> http://v2ex.com https://abc<img />abd';
    print preg_replace('%(?<!"|\')https?://[^\s<]+%', '<a href="$0">$0</a>', $text);
    //<a href="http://abc">http://abc</a><a href="http://xxx">xsx</a> <a href="http://v2ex.com">http://v2ex.com</a> <a href="https://abc">https://abc</a><img />abd
    mozillazg
        7
    mozillazg  
       2013-01-17 09:23:29 +08:00
    ljbha007
        8
    ljbha007  
       2013-01-17 10:17:15 +08:00   ❤️ 1
    正则: (https*:\/\/\w+\.\w+.\(?:\.\w+)*)
    替换:<a href="$1">$1</a>

    PHP的preg和javascript通用
    liuyao729
        9
    liuyao729  
    OP
       2013-01-18 02:54:29 +08:00
    从目前看来没有好的解决办法了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   750 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:31 · PVG 05:31 · LAX 14:31 · JFK 17:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.