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 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错