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条)

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页