简体   繁体   English

php preg_match,不适用于验证URL

[英]php preg_match, not working for validating URL's

Ihave a PHP preg_match regex which is : 我有一个PHP preg_match正则表达式是:

#^(http:\/\/|https:\/\/|www\.|//)*(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d{1,5}))?([A-Z0-9_-]|\.|\/|\?|\#|=|&|%)*$#i

The problem is when I try to match any URL ending with .com&& , it returns true, but as expected it should return false, what could be possibly wrong with it? 问题是当我尝试匹配任何以.com &&结尾的URL时,它返回true,但是按预期它应该返回false,这可能是什么问题?

I am using it as: 我将其用作:

    function isValidURL($url) {
        if (preg_match("#^(http:\/\/|https:\/\/|www\.|//)*(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d{1,5}))?([A-Z0-9_-]|\.|\/|\?|\#|=|&|%)*$#i", $url)) {
            return true;
        }else{
            return false;
        }
    }

and accessing it as: 并以以下方式访问它:

$URL = $_GET['url'];
echo var_dump(isValidURL($URL));

Now if I open the page as /url.php?url=http://www.google.com it returns true, if I open page as /url.php?url=http://www.google.com** it returns false. 现在,如果我以/url.php?url=http://www.google.com打开页面,则返回true,如果我以/url.php?url=http://www.google.com**打开页面/url.php?url=http://www.google.com**它返回false。 If I open the page as /url.php?url=http://www.google.com&& it returns true but it should return false as .com&& is not a valid TLD. 如果我以/url.php?url=http://www.google.com&&打开页面,则返回true,但由于.com &&不是有效的TLD,它应该返回false。

Your bit here at the end... 最后一点

([A-Z0-9_-]|\.|\/|\?|\#|=|&|%)*

is what's matching the ampersands. 是匹配“&”号的东西。 What you probably want to do is require a prefixed question mark if there's a query string: 您可能想做的是,如果有查询字符串,则需要带前缀的问号:

(\?([A-Z0-9_-]|\.|\/|\?|\#|=|&|%)*)?

However, there's a better way to do this in PHP 5.2+: 但是,在PHP 5.2+中有一种更好的方法:

var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL));

http://www.php.net/manual/en/filter.filters.validate.php http://www.php.net/manual/zh-CN/filter.filters.validate.php

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

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