• 请不要在回答技术问题时复制粘贴 AI 生成的内容
liuyao729
V2EX  ›  程序员

求一段正则 链接

  •  
  •   liuyao729 · Jan 16, 2013 · 3830 views
    This topic created in 4915 days ago, the information mentioned may be changed or developed.
    把 字符串中没有加链接的 url 加上链接 有的就不用了。
    $str = '<a href="xxxx">xsx</a> http://www.sunp.eu.org ';
    显示成
    <a href="xxxx">xsx</a> <a href="http://www.sunp.eu.org">http://www.sunp.eu.org</a>
    9 replies    1970-01-01 08:00:00 +08:00
    jeffrey
        1
    jeffrey  
       Jan 16, 2013
    mozillazg
        2
    mozillazg  
       Jan 16, 2013   ❤️ 1
    个人觉得求正则的话,提问者应该至少说明三件事:
    * 使用的程序语言或工具
    * 待处理字符串特征及示例
    * 结果字符串的细节约束
    上面几点不讲清楚的话,回答者会搞不清楚提问者的具体需求,提问者也得不到想要的正则。
    mozillazg
        3
    mozillazg  
       Jan 16, 2013
    [^"']https?://\S+
    clowwindy
        4
    clowwindy  
       Jan 16, 2013   ❤️ 1
    liuyao729
        5
    liuyao729  
    OP
       Jan 17, 2013
    mozillazg
        6
    mozillazg  
       Jan 17, 2013
    @liuyao729 首先声明,我不会 PHP 也没有测试环境,只是上网查了一下 PHP 的替换函数。
    用了一个在线执行 PHP 代码的网站进行的测试(PHP5),
    该正则比较简陋并且对 <a href="http://xx?q=http://"></a> 会误判:
    $text = 'http://abc<a href="http://xxx">xsx</a> http://sunp.eu.org 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://sunp.eu.org">http://sunp.eu.org</a> <a href="https://abc">https://abc</a><img />abd
    mozillazg
        7
    mozillazg  
       Jan 17, 2013
    ljbha007
        8
    ljbha007  
       Jan 17, 2013   ❤️ 1
    正则: (https*:\/\/\w+\.\w+.\(?:\.\w+)*)
    替换:<a href="$1">$1</a>

    PHP的preg和javascript通用
    liuyao729
        9
    liuyao729  
    OP
       Jan 18, 2013
    从目前看来没有好的解决办法了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2676 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 16:07 · PVG 00:07 · LAX 09:07 · JFK 12:07
    ♥ Do have faith in what you're doing.