代码之家  ›  专栏  ›  技术社区  ›  donohoe

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

  •  2
  • donohoe  · 技术社区  · 17 年前

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

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

    好域名:example.com

    来自example.com的优秀URL:

    因此,不来自example.com的坏URL:

    一些注意事项:

    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`!()\[\]{};:'".,<>?«»“”‘’]))
    

    见他的帖子: An Improved Liberal, Accurate Regex Pattern for Matching URLs

    5 回复  |  直到 15 年前
        1
  •  7
  •   D. Evans    17 年前

    你必须使用正则表达式吗?PHP有很多内置函数来做这类事情。

    filter_var($url, FILTER_VALIDATE_URL)
    

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

        $domain = parse_url($url, PHP_URL_HOST);
    

    将告诉您它所指的域。

        2
  •  5
  •   Peter Bailey    17 年前

    我的刺

    <?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>";
      }
    }
    
        3
  •  1
  •   Douglas Leeder    17 年前

    也许:

    ^https?://[^/]*blah\.com(|/.*)$
    

    编辑:

    http://editblah.com

    ^https?://(([^/]*\.)|)blah\.com(|/.*)$
    
        4
  •  0
  •   Jeremy Stein    17 年前
    \b(https?)://([-A-Z0-9]+\.)*blah.com(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)?
    
        5
  •  0
  •   chaos    17 年前
    !^https?://(?:[a-zA-Z0-9-]+\.)*blah\.com(?:/[^#]*(?:#[^#]+)?)?$!