我想匹配墙贴中的网址链接并将此链接替换为锚标记,为此我使用下面的正则表达式。
我想匹配4种类型的网址:
http://example.com
https://example.com
www.example.com
example.com
preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@',
'<a href="$1">$1</a>', $subject);
此表达式仅匹配前两种类型的网址。
如果我将此表达式用于匹配url模式
'@(www?([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@'
,然后它只匹配第三种类型的网址模式。
如何将所有四种类型的网址格式与单个正则表达式匹配?
答案 0 :(得分:15)
说实话,我会使用不同的正则表达式。就像2009年Gruber posted中的那个:
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
或2010年Gruber posted的更新版本(感谢@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`!()\[\]{};:'".,<>?«»“”‘’]))
答案 1 :(得分:15)
使用 Nev Stokes 给定链接的完整工作示例:
public function clickableUrls($html){
return $result = preg_replace(
'%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s',
'<a href="$1">$1</a>',
$html
);
}
答案 2 :(得分:2)
^((([hH][tT][tT][pP][sS]?)\:\/\/)?([\w\\-]+(\[\w\.\&%\$\-]+)*)?((([^\s\(\)\<\>\\\"\.\ [\]\,;:]+)(\.[^\s\(\)\<\>\\\"\.\[\]\,;:]+)*(\.[a-zA-Z]{2,4}))|((([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])))(\b\:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b)?((\/[^\/][\w\.\,\?\'\\\/\+&%\$#\=~_\-]*)*[^\.\,\?\"\'\(\)\[\]!;<>{}\s\x7F-\xFF])?)$
在debuggex上查看。
答案 3 :(得分:1)
我刚刚查过这篇文章(2年后)可能是你得到了答案但是对于初学者来说,你可以使用正则表达式去除每种类型的URL或查询字符串
(https|http|ftp)\:\/\/|([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4})|\?([a-zA-Z0-9]+[\&\=\#a-z]+)
它将删除每种类型的URL,请查看以下列表。我使用不同类型的域名给那些想要问“它是否会删除.us,.in或.pk等类型的域名。
工作示例(在PHP5 +,Apache2 +中测试):
$str = "ftp://www.web.com, web.net, www.website.info, website.us, web.ws?query=true, www.web.biz?query=true, ftp://web.in?query=true, media.google.com hello world, working more with ns ns.google.pk or ww1.smart.au and www3.smart.br w1.smart.so ?ques==two&t=p http://website.info?ques==two&t=p https://www.weborwebsite.com and ftp://www.hotmail.br";
echo preg_replace("/(https|http|ftp)\:\/\/|([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4})|([a-z0-9A-Z]+\.[a-zA-Z]{2,4})|\?([a-zA-Z0-9]+[\&\=\#a-z]+)/i", "", $str);
它会返回
, , , , , , , hello world, working more with ns or and and
希望它可以帮助很多编码人员
答案 4 :(得分:0)
如果你想让那个工作,你需要让“https?//”部分可选,因为你似乎对regexp有相当好的把握,我不会告诉你,对读者来说是一个优秀的:)
但我普遍同意内华达州的观点,但它的作用过于复杂。
答案 5 :(得分:0)
使用此模式。
$regex = "(https?\:\/\/|ftp\:\/\/|www\.|[a-z0-9-]+)+([a-z0-9-]+)\.+([a-z]{2,4})((\/|\.)+([a-z0-9-_.\/]*)$|$)";
希望有所帮助。
答案 6 :(得分:0)
我的两分钱(五年后!):
preg_match("/^((https|http|ftp)\:\/\/)?([a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4}|[a-z0-9A-Z]+\.[a-z0-9A-Z]+\.[a-zA-Z]{2,4}|[a-z0-9A-Z]+\.[a-zA-Z]{2,4})$/i", $url)
希望它有助于某人
答案 7 :(得分:0)
这对我非常有用-包括mailto检查:
d1 = {1:2, 3:4, 5:6, 7:9}