此URL验证不能正常工作


This URL validation is not working properly

我有一个代码,我从另一个stackoverflow帖子,

在这里,

 function validate_url($url)
 {
     $pattern = "/^((ht|f)tp(s?)':'/'/|~/|/)?([w]{2}(['w'-]+'.)+(['w]{2,5}))(:['d]{1,5})?/";
     if (!preg_match($pattern, $url))
     {
         $this->form_validation->set_message('validate_url', 'The URL you entered is not correctly formatted.'); 
         return false;
     }
     return false;
 }

它不能正常工作。它允许URL不带。com或。in(点之后的任何东西)。

意思是,它应该允许适当的URL作为http://something.com或http://www.something.in或

但不是http://something(没有。in或。com或任何其他)或或者www.something

我不太了解正则表达式。

看看这个网站:

https://mathiasbynens.be/demo/url-regex

它包含了很多不同的URL验证正则表达式。

来自Diego Perini:

_^(?:(?:https?|ftp)://)(?:'S+(?::'S*)?@)?(?:(?!10(?:'.'d{1,3}){3})(?!127(?:'.'d{1,3}){3})(?!169'.254(?:'.'d{1,3}){2})(?!192'.168(?:'.'d{1,3}){2})(?!172'.(?:1[6-9]|2'd|3[0-1])(?:'.'d{1,3}){2})(?:[1-9]'d?|1'd'd|2[01]'d|22[0-3])(?:'.(?:1?'d{1,2}|2[0-4]'d|25[0-5])){2}(?:'.(?:[1-9]'d?|1'd'd|2[0-4]'d|25[0-4]))|(?:(?:[a-z'x{00a1}-'x{ffff}0-9]+-?)*[a-z'x{00a1}-'x{ffff}0-9]+)(?:'.(?:[a-z'x{00a1}-'x{ffff}0-9]+-?)*[a-z'x{00a1}-'x{ffff}0-9]+)*(?:'.(?:[a-z'x{00a1}-'x{ffff}]{2,})))(?::'d{2,5})?(?:/[^'s]*)?$_iuS

似乎比filter_var使用的要好得多。

您可以使用filter_var filter_var('http://example.com', FILTER_VALIDATE_URL);验证您的url。在这里您可以找到您可以使用的所有类型的验证类型。如果您需要http(s),您可以添加use this.

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

使用

<?php
$url = "http://something";
if ((!filter_var($url, FILTER_VALIDATE_URL) === false) && @fopen($url,"r")) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");
}
?>

或者使用

<?php
$url = 'http://example';
if(validateURL($url)){
       echo "Valid";
    }else{
        echo "invalid";
    }
function validateURL($URL) {
      $pattern_1 = "/^(http|https|ftp):'/'/(([A-Z0-9][A-Z0-9_-]*)('.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:('d+))?'/?/i";
      $pattern_2 = "/^(www)(('.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:('d+))?'/?/i";       
      if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
        return true;
      } else{
        return false;
      }
    }
?>

您可以使用以下正则表达式

$url = 'http://something.com';
$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$/", $url)) {
    echo "Matched";
} else {
    echo "Not Matched";
}