dongzizhi9903 2016-01-12 06:31
浏览 24
已采纳

PHP文本到HTML href链接(忽略图像链接)与正则表达式[重复]

This question already has an answer here:

I need regular expression that converts links in plain text to HTML links. my code is:

preg_replace('/(((f|ht){1}tps:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                   '<a href="\\1" target="_blank">\\1</a>', $text);

but this expression will make the image url to href as well. so my question is how to avoid if the url is in img tag like.

The text: https://yahoo.com this is my image <img src="https://img.com/img.jpg">

The result with my expression:<a href="https://yahoo.com">https://yahoo.com</a> this is my image <img src="<a href="https://img.com/img.jpg">https://img.com/img.jpg</a>">

i want this one <a href="https://yahoo.com">https://yahoo.com</a> this is my image <img src="http://img.com/img.jpg">

</div>
  • 写回答

2条回答 默认 最新

  • doukong9982 2016-01-12 06:55
    关注

    It's possible using negative lookbehind operator (?<!text), though probably not the most efficient way since the engine will back track a lot. Maybe you could do strip_tags('img') before preg_replace?

    Another drawback of lookbehind is that it has to be fixed length. This means you cannot grab onto img since there may be additional attributes between it and the src. Anyhow, if you're really tempted to use it, your regex would look like this

    preg_replace('/(?<!src=[\'"])(((f|ht){1}tps?:\/\/)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/i',
                   '<a href="\\1" target="_blank">\\1</a>', $text);
    

    Also, no need for second expression, as Gavriel points out, just add an s?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料