使用PHP preg_match检测URL,允许缺少www

时间:2013-12-28 16:24:56

标签: php url preg-match

允许缺少链接preg_match部分的PHP网址www.代码是什么?

普通的preg_match网址代码:

%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i

我试过这个:

%^((https?://)|([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i

额外背景:

这是用于检查用户输入的if语句。

elseif (!preg_match("%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i",$link)){
   $linkErr = "Please enter a valid URL.";
}

3 个答案:

答案 0 :(得分:1)

您匹配https?://或www。为什么两者都不存在?

未经测试,只是写下来:

^(https?://)?(www\.)?[a-z]+\.[a-z]{2,3}(:[0-9]+)?(/.*)?$

 https://     www.   google . com       :1234    /blabla.php?foo=bar

答案 1 :(得分:0)

function hasWww($url) {
   $data = parse_url($url);
   if (isset($data['host'])) return strpos($data['host'], 'www.') === 0;
   return false;
}

答案 2 :(得分:0)

尝试在')之间插入(' 试试这个:

preg_match("%^((https?://)|(www\.))?([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i", $link);