V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
liuyao729
V2EX  ›  程序员

求一段正则 链接

  •  
  •   liuyao729 · 2013 年 1 月 16 日 · 3606 次点击
    这是一个创建于 4751 天前的主题,其中的信息可能已经有所发展或是发生改变。
    把 字符串中没有加链接的 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 年 1 月 16 日
    mozillazg
        2
    mozillazg  
       2013 年 1 月 16 日   ❤️ 1
    个人觉得求正则的话,提问者应该至少说明三件事:
    * 使用的程序语言或工具
    * 待处理字符串特征及示例
    * 结果字符串的细节约束
    上面几点不讲清楚的话,回答者会搞不清楚提问者的具体需求,提问者也得不到想要的正则。
    mozillazg
        3
    mozillazg  
       2013 年 1 月 16 日
    [^"']https?://\S+
    clowwindy
        4
    clowwindy  
       2013 年 1 月 16 日   ❤️ 1
    liuyao729
        5
    liuyao729  
    OP
       2013 年 1 月 17 日
    mozillazg
        6
    mozillazg  
       2013 年 1 月 17 日
    @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 年 1 月 17 日
    ljbha007
        8
    ljbha007  
       2013 年 1 月 17 日   ❤️ 1
    正则: (https*:\/\/\w+\.\w+.\(?:\.\w+)*)
    替换:<a href="$1">$1</a>

    PHP的preg和javascript通用
    liuyao729
        9
    liuyao729  
    OP
       2013 年 1 月 18 日
    从目前看来没有好的解决办法了
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   2650 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:28 · PVG 23:28 · LAX 07:28 · JFK 10:28
    ♥ Do have faith in what you're doing.