检查字符串是否只包含 PHP 中的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15011508/
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-25 08:22:08  来源:igfitidea点击:

Check if a string contains nothing but an URL in PHP

phpurlvalidation

提问by yan

I am wondering if this is a proper way to check, if a string contains nothing but an URL:

我想知道这是否是检查字符串是否只包含 URL 的正确方法:

if (stripos($string, 'http') == 0 && !preg_match('/\s/',$string)) {
  do_something();
}

stripos() checks if the string starts with "http"
preg_match() checks if the string contains spaces

stripos() 检查字符串是否以“http”开头
preg_match() 检查字符串是否包含空格

If not so, I assume that the string is nothing but an URL - but is that assumption valid? Are there better ways to achieve this?

如果不是这样,我假设该字符串只是一个 URL - 但这种假设是否有效?有没有更好的方法来实现这一目标?

回答by John Conde

Use filter_var()

filter_var()

if (filter_var($string, FILTER_VALIDATE_URL)) { 
  // you're good
}

The filters can be even more refined. See the manualfor more on this.

过滤器可以更精细。有关更多信息,请参阅手册

回答by Winston

In PHP there is a better way to validate the URL http://www.php.net/manual/en/function.filter-var.php

在 PHP 中有一种更好的方法来验证 URL http://www.php.net/manual/en/function.filter-var.php

if(filter_var('http://example.com', FILTER_VALIDATE_URL)))
    echo 'this is URL';

回答by CFP Support

To more securely validate URLs (and those 'non-ascii' ones), you can

要更安全地验证 URL(以及那些“非 ascii”),您可以

  1. Check with the filter (be sure to check the manualon which filter suits for your situation)
  2. Check to see if there are DNS records
  1. 检查过滤器(请务必检查适合您情况的过滤器的手册
  2. 查看是否有DNS记录

$string = idn_to_ascii($URL); if(filter_var($string, FILTER_VALIDATE_URL) && checkdnsrr($string, "A")){ // you have a valid URL }

$string = idn_to_ascii($URL); if(filter_var($string, FILTER_VALIDATE_URL) && checkdnsrr($string, "A")){ // you have a valid URL }