简体   繁体   English

使用正则表达式对旧php版本进行网址验证

[英]Url validation with regex for old php version

Note : I'm using an older PHP version so FILTER_VALIDATE_URL is not available at this time. 注意 :我使用的是较早的PHP版本,因此FILTER_VALIDATE_URL目前不可用。

After many many searches I am still unable to find the exact answer that can cover all URL structure possibilities but at the end I'm gonna use this way: 经过许多次搜索后,我仍然找不到能够涵盖所有URL结构可能性的确切答案,但最后我将使用这种方式:

I'm using the following function 我正在使用以下功能

1) Function to get proper scheme 1)获得适当方案的功能

function convertUrl ($url){
    $pattern = '#^http[s]?://#i';
    if(preg_match($pattern, $url) == 1) { // this url has proper scheme
        return $url;
    } else {
        return 'http://' . $url;
    }
}

2) Conditional to check if it is a URL or not 2)有条件检查是否为URL

if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
  echo "URL is valid";
}else {
  echo "URL is invalid<br>";
}

Guess What!? 你猜怎么了!? It works so perfect for all of these possibilities: 它非常适合所有这些可能性:

$url = "google.com";
$url = "www.google.com";
$url = "http://google.com";
$url = "http://www.google.com";
$url = "https://google.com";
$url = "https://www.codgoogleekarate.com";
$url = "subdomain.google.com";
$url = "https://subdomain.google.com";

But still have this edge case 但是仍然有这种情况

$url = "blahblahblahblah";

The function convertUrl($url) will convert this to $url = "http://blahblahblahblah"; 函数convertUrl($url)会将其转换为$url = "http://blahblahblahblah"; then the regex will consider it as valid URL while it isn't!! 那么正则表达式会认为它是有效URL,而实际上不是!

How can I edit it so that it won't pass a URL with this structure http://blahblahblahblah 我如何编辑它,以便它不会传递具有此结构的URL http://blahblahblahblah

如果要验证Internet网址 ,请在正则表达式中添加检查点是否包含点(。)字符。

Note: http://blahblahblah is a valid url as is http://localhost

Try this: 尝试这个:

if (preg_match("/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/", $url)) {
  echo "URL is valid";
}else {
  echo "URL is invalid<br>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM