使用正则表达式匹配php中的url模式 [英] match url pattern in php using regular expression

查看:88
本文介绍了使用正则表达式匹配php中的url模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配墙上帖子中的url链接,并用锚标记替换此链接,为此,我使用下面的正则表达式.

I want to match a url link in wall post and replace this link with anchor tag, for this I use the regular expression below.

我想要匹配4种类型的url:

I would like the match 4 types of url:

  1. http://example.com
  2. https://example.com
  3. www.example.com
  4. example.com
  1. http://example.com
  2. https://example.com
  3. www.example.com
  4. example.com

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

此表达式仅匹配前两种网址.

This expression matches only first two types of url.

如果我将此表达式用于匹配网址格式 '@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@',则仅匹配第三种类型的网址格式.

If I use this expression for match url pattern '@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', then it only matches the third type of url pattern.

如何用单个正则表达式匹配所有四种类型的url模式?

How can I match all four type of url pattern with a single regular expression?

推荐答案

老实说,我会使用其他正则表达式.格鲁伯(Gruber)在2009年发布了这样的内容:

I'd use a different regex to be honest. Like this one that Gruber posted in 2009:

\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))

或Gruber在2010年发布的更新版本(感谢@IMSoP):

or this updated version that Gruber posted in 2010 (thanks, @IMSoP):

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""‘’]))

这篇关于使用正则表达式匹配php中的url模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆