php 检查字符串是否为 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9623007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:17:40  来源:igfitidea点击:

check if a string is a URL

phpregexurl

提问by Reham Fahmy

I've seen many questions but wasn't able to understand how it works as I want a more simple case.

我看过很多问题,但无法理解它是如何工作的,因为我想要一个更简单的案例。

If we have text, whatever it is, I'd like to check if it is a URL or not.

如果我们有文本,不管它是什么,我想检查它是否是一个 URL。

$text = "something.com"; //this is a url

if (!IsUrl($text)){
    echo "No it is not url";
    exit; // die well
}else{
    echo "Yes it is url";
    // my else codes goes
}

function IsUrl($url){
    // ???
}

Is there any other way rather than checking with JavaScript in the case JS is blocked?

在 JS 被阻止的情况下,除了使用 JavaScript 进行检查之外,还有其他方法吗?

回答by enygma

PHP's filter_varfunction is what you need. Look for FILTER_VALIDATE_URL. You can also set flagsto fine-tune your implementation.
No regex needed....

PHP 的filter_var功能正是您所需要的。寻找FILTER_VALIDATE_URL. 您还可以设置flags微调您的实现。
不需要正则表达式....

回答by user3078359

The code below worked for me:

下面的代码对我有用:

if(filter_var($text, FILTER_VALIDATE_URL))
{
    echo "Yes it is url";
    exit; // die well
}
else
{
    echo "No it is not url";
   // my else codes goes
}

You can also specify RFCcompliance and other requirements on the URL using flags. See PHP Validate Filtersfor more details.

您还可以使用标志在 URL 上指定RFC合规性和其他要求。有关更多详细信息,请参阅PHP 验证过滤器

回答by JKirchartz

http://www.php.net/manual/en/function.preg-match.php#93824

http://www.php.net/manual/en/function.preg-match.php#93824

<?php 
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME 
    $regex .= "([a-z0-9+!*(),;?&=$_.-]+(\:[a-z0-9+!*(),;?&=$_.-]+)?@)?"; // User and Pass 
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP 
    $regex .= "(\:[0-9]{2,5})?"; // Port 
    $regex .= "(\/([a-z0-9+$_-]\.?)+)*\/?"; // Path 
    $regex .= "(\?[a-z+&$_.-][a-z0-9;:@&%=+\/$_.-]*)?"; // GET Query 
    $regex .= "(#[a-z_.-][a-z0-9+$_.-]*)?"; // Anchor 

       if(preg_match("/^$regex$/i", $url)) // `i` flag for case-insensitive
       { 
               return true; 
       } 
?>

but your example URL is over simplified, (\w+)\.(\w+)would match it. somebody else mentioned filter_varwhich is simply a filter_var($url, FILTER_VALIDATE_URL)but it doesn't seem to like non-asciicharacters so, beware...

但您的示例 URL 过于简化,(\w+)\.(\w+)将匹配它。其他人提到filter_var这只是一个filter_var($url, FILTER_VALIDATE_URL)但它似乎不喜欢非 ascii字符所以,当心......

回答by Sindre

Check if it is a valid url (example.com IS NOTa valid URL)

检查它是否是一个有效的网址(example.com不是一个有效的网址)

    function isValidURL($url)
    {
        return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*
        (:[0-9]+)?(/.*)?$|i', $url);
    }

How to use the function:

如何使用该功能:

    if(!isValidURL($fldbanner_url))
    {
        $errMsg .= "* Please enter valid URL including http://<br>";
    }

Source: http://phpcentral.com/208-url-validation-in-php.html

来源:http: //phpcentral.com/208-url-validation-in-php.html

回答by greenie2600

Regexes are a poor way to validate something as complex as a URL.

正则表达式是验证像 URL 这样复杂的东西的糟糕方法。

PHP's filter_var()function offers a much more robust way to validate URLs. Plus, it's faster, since it's native code.

PHP 的filter_var()函数提供了一种更强大的方式来验证 URL。另外,它更快,因为它是本机代码。

回答by kytwb

You could use the following regex pattern to check if your variable is an url or not :

您可以使用以下正则表达式模式来检查您的变量是否为 url:

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

回答by Churk

I don't think there is a definitive answer to this. Example of a valid URL:

我不认为对此有明确的答案。有效 URL 示例:

localhost
http://xxx.xxx.xxx/alkjnsdf
abs.com

If you have some text. and not a large amount of it. You can check by doing a CURL request and see if that returns a valid response. Otherwise if I put localhost, it could be a link and it could be something else and you wouldn't be able check it.

如果你有一些文字。而且数量不多。您可以通过执行 CURL 请求来检查它是否返回有效响应。否则,如果我输入 localhost,它可能是一个链接,也可能是其他内容,您将无法检查它。

回答by anubhava

Something like might work for you:

类似的东西可能对你有用:

$arr = array('abc.com/foo',
'localhost',
'abc+def',
'how r u',
'https://how r u',
'ftp://abc.com',
'a.b');
foreach ($arr as $u) {
   $url = $u;
   if (!preg_match('#^(?:https?|ftp)://#', $url, $m))
      $url = 'http://' . $url;
   echo "$u => ";
   var_dump(filter_var($url, FILTER_VALIDATE_URL));
}

OUTPUT:

输出:

abc.com/foo => string(18) "http://abc.com/foo"
localhost => string(16) "http://localhost"
abc+def => string(14) "http://abc+def"
how r u => bool(false)
https://how r u => bool(false)
ftp://abc.com => string(13) "ftp://abc.com"
a.b => string(10) "http://a.b"

So basically wherever you notice falseas return value that is an INVALID URL for you.

因此,基本上无论您注意到false返回值的任何地方都是无效的 URL。