doupi7619 2014-06-05 15:45
浏览 53
已采纳

将URL转换为链接,除非它们在使用PHP的BBCode中

I have text that supports BBCode and I use a custom PHP function to do the replacing instead of using PECL package or anything. It's working great to turn:

[url=http://www.google.com]Google[/url]

to

<a href="http://www.google.com" target="_blank">Google</a>

I also have a custom BBCode tag that turns the tag into an iframe:

[customtag]abc[/customtag]

to

<iframe src="http://example.com/abc"></iframe>

But now I have a requirement to change urls that are just typed normally to turn them into links. So if you type:

http://www.google.com

it will turn it into:

<a href="http://www.google.com" target="_blank">Google</a>

I've used this regex to do this:

$string = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $string);

But it's also matching what is in bbcode. If I include it after I parse the bbcode then it changes things in the anchor. Also happens for images and the iframe.

So how I can I change plain urls but ignore ones that are within a bbcode tag or already in a html tag?

  • 写回答

1条回答 默认 最新

  • douyouming9180 2014-06-05 15:51
    关注

    This may not be the "best" solution, but you can use a negative lookbehind ((?<!...)) to make sure that the URL isn't prefixed by ', ", or =. The obvious limitations are if someone writes something like:

    Let's visit "https://google.com" on our computers. Or the link=https://google.com.

    Anyways, the negative lookbehind would go at the very beginning of your expression and contain a character class: ["'=].

    (?<!["'=])(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错