dougu7546 2013-11-04 11:10
浏览 32
已采纳

嵌入正则表达式的链接和图像

SO Community!

I am new to regular expressions and I have a trouble with them. I have a chat script with simple parser of user data. There is an ability to embed an image with BBCode tag, like this: [img]http://example.com/image.png[/img]. I also want to do automatic link transformation to valid hyperlinks. I have two processing REGEXes, and I don't know how to solve the conflict between them.

To process [img] tag I use this and it executes first:

$line = preg_replace('/\[img\](https?:\/\/[a-zA-Z0-9%\-_?&=:+.\/]+)\[\/img\]/iU', '<a href="$1" target="_blank"><img class="incl_img" src="$1"></a>', $line, 5);

Then to process links I use this:

$line = preg_replace('#(https?:\/\/([a-zA-Z0-9-.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e', '\'[<a href="$1" title="$1" target="_blank">$2</a>]\'',$line);

And when user posts an image the link processing regex breaks <img> tag by inserting its <a href=... instead of link. How to avoid it without using special [url] tag or something else? How to separate [img] tags from simple links? Any corrections of regexes and/or algorithms are welcome. Thanks in advance!

  • 写回答

2条回答 默认 最新

  • doujia2090 2013-11-07 10:44
    关注

    I solved my problem. The solution is to correct the second regex (URL parser) and add some conditions. New regex will look like this:

    #(?<!src="|href=")(https?:\/\/([a-zA-Z0-9\-\.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e'
    

    And the whole code became this:

    $line = preg_replace('#(?<!src="|href=")(https?:\/\/([a-zA-Z0-9\-\.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e', '\'[<a href="$1" title="$1" target="_blank">$2</a>]\'',$line);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(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报错