drduinfu915094 2013-07-25 17:12
浏览 24
已采纳

正则表达式没有得到特殊字符的完整链接

I am using this code:

$string = preg_replace("~(?!(?:https?://(?:www\.)?|www\.)(?:youtube\.com)(?:https?://(?:www\.)?|www\.)[\w./=?#-]+~i", '<a href="$0">$0</a>', $string);

So that I can turn the link beneath into a clickable link.

http://upload.wikimedia.org/wikipedia/commons/f/f2/Bill_Clinton%2C_Yitzhak_Rabin,%2C_Yasser_Arafat_at_the_White_House_1993-09-13.jpg

This works for a part... It makes a link of http://upload.wikimedia.org/wikipedia/commons/f/f2/Bill_Clinton but the rest stays plain text. How can I make it work for the whole link? So you see a comma too... How can I make that a link?

  • 写回答

1条回答 默认 最新

  • dongyanjing5975 2013-07-25 17:31
    关注

    Also I'm trying to account for punctuation at the end of a URL (so that we don't include it).

    <?php
    
    $string = "This works http://upload.wikimedia.org/wikipedia/commons/f/f2/Bill_Clinton%2C_Yitzhak_Rabin%2C_Yasser_Arafat_at_the_White_House_1993-09-13.jpg. This one should fail http://www.youtube.com/v/adlskdfjasopie. Although this one should fail as well http://youtu.be/adlkajdaslk.";
    
    $string = preg_replace("~(?!(?:https?://(?:www\.)?|www\.)(?:youtu))(?:https?://(?:www\.)?|www\.)[^\s]+[^.!?,\<\]\[\)(]~i",'<a href="$0">$0</a>',$string);
    
    
    ?>
    

    output

    This works <a href="http://upload.wikimedia.org/wikipedia/commons/f/f2/Bill_Clinton%2C_Yitzhak_Rabin%2C_Yasser_Arafat_at_the_White_House_1993-09-13.jpg. ">http://upload.wikimedia.org/wikipedia/commons/f/f2/Bill_Clinton%2C_Yitzhak_Rabin%2C_Yasser_Arafat_at_the_White_House_1993-09-13.jpg. </a>This one should fail http://www.youtube.com/v/adlskdfjasopie. Although this one should fail as well http://youtu.be/adlkajdaslk.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭