使用正则表达式进行特定域URL验证

don*_*hoe 2 php regex

我一直在尝试自己,并在网上搜索,写这个正则表达式,但没有成功.

我需要验证给定的URL是来自特定域和格式良好的链接(在PHP中).例如:

好域名:example.com

来自example.com的好网址:

如此糟糕的网址不是来自example.com:

一些注意事项:我不关心"http"verus"https"但是如果它对你很重要则假设"http"总是使用这个正则表达式的代码是PHP所以加分.

2010年更新:

Gruber添加了一个很棒的URL正则表达式:

?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
Run Code Online (Sandbox Code Playgroud)

请参阅他的帖子:改进的自由,准确的匹配URL的正则表达式模式

D. *_*ans 7

你必须使用正则表达式吗?PHP有许多内置函数来执行此类操作.

filter_var($url, FILTER_VALIDATE_URL)
Run Code Online (Sandbox Code Playgroud)

将告诉您URL是否有效,以及

    $domain = parse_url($url, PHP_URL_HOST);
Run Code Online (Sandbox Code Playgroud)

会告诉你它引用的域名.

它可能比一些疯狂的正则表达式更清晰,更易于维护.


Pet*_*ley 5

我刺伤了它

<?php

$pattern = "#^https?://([a-z0-9-]+\.)*blah\.com(/.*)?$#";

$tests = array(
    'http://blah.com/so/this/is/good'
  , 'http://blah.com/so/this/is/good/index.html'
  , 'http://www.blah.com/so/this/is/good/mice.html#anchortag'
  , 'http://anysubdomain.blah.com/so/this/is/good/wow.php'
  , 'http://anysubdomain.blah.com/so/this/is/good/wow.php?search=doozy'
  , 'http://any.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
  , 'http://999.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
  , 'http://obviousexample.com'
  , 'http://bbc.co.uk/blah.com/whatever/you/get/the/idea'
  , 'http://blah.com.example'
  , 'not/even/a/blah.com/url'
);

foreach ( $tests as $test )
{
  if ( preg_match( $pattern, $test ) )
  {
    echo $test, " <strong>matched!</strong><br>";
  } else {
    echo $test, " <strong>did not match.</strong><br>";
  }
}

//  Here's another way
echo '<hr>';
foreach ( $tests as $test )
{
  if ( $filtered = filter_var( $test, FILTER_VALIDATE_URL ) )
  {
    $host = parse_url( $filtered, PHP_URL_HOST );
    if ( $host && preg_match( "/blah\.com$/", $host ) )
    {
      echo $filtered, " <strong>matched!</strong><br>";
    } else {
      echo $filtered, " <strong>did not match.</strong><br>";
    }
  } else {
    echo $test, " <strong>did not match.</strong><br>";
  }
}
Run Code Online (Sandbox Code Playgroud)