복붙노트

URL에 대한 PHP 유효성 검사 / 정규식

PHP

URL에 대한 PHP 유효성 검사 / 정규식

URL에 대한 간단한 정규식을 찾고 있었는데, 누구든지 잘 작동하는가요? 젠드 프레임 워크 유효성 검사 클래스를 찾지 못했고 몇 가지 구현을 보았습니다.

감사

해결법

  1. ==============================

    1.

    나는 이것을 몇 가지 프로젝트에서 사용했지만 문제가 발생했다고 생각하지 않지만 철저하지는 않습니다.

    $text = preg_replace(
      '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
      "'<a href=\"$1\" target=\"_blank\">$3</a>$4'",
      $text
    );
    

    끝에있는 임의의 정크의 대부분은 http://domain.com과 같은 상황을 처리하는 것입니다. (마침표와 일치하지 않도록). 나는 그것이 정리 될 수 있었지만 그것이 효과가 있었기 때문에 확신한다. 나는 그저 프로젝트에서 프로젝트로 복사 한 것뿐입니다.

  2. ==============================

    2.

    filter_var () 함수를 사용하여 문자열이 URL인지 여부를 검증하십시오.

    var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
    

    불필요한 경우 정규식을 사용하는 것은 나쁜 습관입니다.

    편집 : 조심해,이 솔루션은 유니 코드 - 안전하지 않으며 XSS - 안전하지 않습니다. 복잡한 검증이 필요한 경우 어딘가 다른 곳을 찾는 것이 더 나을 것입니다.

  3. ==============================

    3.

    PHP 매뉴얼에 따라 - parse_url은 URL 유효성 검사에 사용되어서는 안됩니다.

    불행히도 filter_var ( 'example.com', FILTER_VALIDATE_URL)이 더 나은 성능을 발휘하지 못하는 것으로 보입니다.

    parse_url () 및 filter_var ()는 모두 http : //와 같은 형식이 잘못된 URL을 전달합니다.

    따라서이 경우 regex가 더 나은 방법입니다.

  4. ==============================

    4.

    만약 당신이 정말로 URL이 있는지 알고 싶다면 :

    function url_exist($url){//se passar a URL existe
        $c=curl_init();
        curl_setopt($c,CURLOPT_URL,$url);
        curl_setopt($c,CURLOPT_HEADER,1);//get the header
        curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
        curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
        curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
        if(!curl_exec($c)){
            //echo $url.' inexists';
            return false;
        }else{
            //echo $url.' exists';
            return true;
        }
        //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);
        //return ($httpcode<400);
    }
    
  5. ==============================

    5.

    존 그루버 (대담한 불 덩어리) :

    정규식 :

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

    preg_match ()에서 사용 :

    preg_match("/(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", $url)
    

    다음은 확장 된 정규식 패턴입니다 (주석 포함).

    (?xi)
    \b
    (                       # Capture 1: entire matched URL
      (?:
        https?://               # http or https protocol
        |                       #   or
        www\d{0,3}[.]           # "www.", "www1.", "www2." … "www999."
        |                           #   or
        [a-z0-9.\-]+[.][a-z]{2,4}/  # looks like domain name followed by a slash
      )
      (?:                       # One or more:
        [^\s()<>]+                  # Run of non-space, non-()<>
        |                           #   or
        \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
      )+
      (?:                       # End with:
        \(([^\s()<>]+|(\([^\s()<>]+\)))*\)  # balanced parens, up to 2 levels
        |                               #   or
        [^\s`!()\[\]{};:'".,<>?«»“”‘’]        # not a space or one of these punct chars
      )
    )
    

    자세한 내용은 다음을 참조하십시오. http://daringfireball.net/2010/07/improved_regex_for_matching_urls

  6. ==============================

    6.

    정규 표현식을 사용하는 것이이 경우에해야 할 현명한 방법이라고 생각하지 않습니다. 모든 가능성에 부합하는 것은 불가능합니다. 그렇더라도 URL이 단순히 존재하지 않을 가능성은 여전히 ​​있습니다.

    다음은 url이 실제로 존재하고 읽을 수 있는지 테스트하는 매우 간단한 방법입니다.

    if (preg_match("#^https?://.+#", $link) and @fopen($link,"r")) echo "OK";
    

    (preg_match가 없으면 서버의 모든 파일 이름의 유효성을 검사합니다)

  7. ==============================

    7.

        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;
          }
        }
    
  8. ==============================

    8.

    나는 이것을 좋은 성공과 함께 사용했다 - 나는 그것을 어디에서 얻었는지 기억하지 않는다.

    $pattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
    
  9. ==============================

    9.

    그리고 당신의 대답 =) 그것을 끊으려고, 당신은 할 수 없어!

    function link_validate_url($text) {
    $LINK_DOMAINS = 'aero|arpa|asia|biz|com|cat|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|local';
      $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array( // @TODO completing letters ...
        "&#x00E6;", // æ
        "&#x00C6;", // Æ
        "&#x00C0;", // À
        "&#x00E0;", // à
        "&#x00C1;", // Á
        "&#x00E1;", // á
        "&#x00C2;", // Â
        "&#x00E2;", // â
        "&#x00E5;", // å
        "&#x00C5;", // Å
        "&#x00E4;", // ä
        "&#x00C4;", // Ä
        "&#x00C7;", // Ç
        "&#x00E7;", // ç
        "&#x00D0;", // Ð
        "&#x00F0;", // ð
        "&#x00C8;", // È
        "&#x00E8;", // è
        "&#x00C9;", // É
        "&#x00E9;", // é
        "&#x00CA;", // Ê
        "&#x00EA;", // ê
        "&#x00CB;", // Ë
        "&#x00EB;", // ë
        "&#x00CE;", // Î
        "&#x00EE;", // î
        "&#x00CF;", // Ï
        "&#x00EF;", // ï
        "&#x00F8;", // ø
        "&#x00D8;", // Ø
        "&#x00F6;", // ö
        "&#x00D6;", // Ö
        "&#x00D4;", // Ô
        "&#x00F4;", // ô
        "&#x00D5;", // Õ
        "&#x00F5;", // õ
        "&#x0152;", // Œ
        "&#x0153;", // œ
        "&#x00FC;", // ü
        "&#x00DC;", // Ü
        "&#x00D9;", // Ù
        "&#x00F9;", // ù
        "&#x00DB;", // Û
        "&#x00FB;", // û
        "&#x0178;", // Ÿ
        "&#x00FF;", // ÿ 
        "&#x00D1;", // Ñ
        "&#x00F1;", // ñ
        "&#x00FE;", // þ
        "&#x00DE;", // Þ
        "&#x00FD;", // ý
        "&#x00DD;", // Ý
        "&#x00BF;", // ¿
      )), ENT_QUOTES, 'UTF-8');
    
      $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
        "&#x00DF;", // ß
      )), ENT_QUOTES, 'UTF-8');
      $allowed_protocols = array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal');
    
      // Starting a parenthesis group with (?: means that it is grouped, but is not captured
      $protocol = '((?:'. implode("|", $allowed_protocols) .'):\/\/)';
      $authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w". $LINK_ICHARS ."\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
      $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*('. $LINK_DOMAINS .'|[a-z]{2}))?)';
      $ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
      $ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
      $port = '(?::([0-9]{1,5}))';
    
      // Pattern specific to external links.
      $external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';
    
      // Pattern specific to internal links.
      $internal_pattern = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]]+)";
      $internal_pattern_file = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]\.]+)$/i";
    
      $directories = "(?:\/[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'#!():;*@\[\]]*)*";
      // Yes, four backslashes == a single backslash.
      $query = "(?:\/?\?([?a-z0-9". $LINK_ICHARS ."+_|\-\.~\/\\\\%=&,$'():;*@\[\]{} ]*))";
      $anchor = "(?:#[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
    
      // The rest of the path for a standard URL.
      $end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';
    
      $message_id = '[^@].*@'. $domain;
      $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
      $news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';
    
      $user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
      $email_pattern = '/^mailto:'. $user .'@'.'(?:'. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';
    
      if (strpos($text, '<front>') === 0) {
        return false;
      }
      if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
        return false;
      }
      if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
        return false;
      }
      if (preg_match($internal_pattern . $end, $text)) {
        return false;
      }
      if (preg_match($external_pattern . $end, $text)) {
        return false;
      }
      if (preg_match($internal_pattern_file, $text)) {
        return false;
      }
    
      return true;
    }
    
  10. ==============================

    10.

    편집하다: 이 코드가 지적했듯이 PHP 5.3.0 (2009-06-30)의 릴리스와 함께 사용이 권장되지 않았으므로 이에 따라 사용해야합니다.

    그냥 내 두 센트지만,이 기능을 개발하고 잠시 동안 그것을 성공으로 사용하고 있습니다. 잘 문서화되고 분리되어있어서 쉽게 변경할 수 있습니다.

    // Checks if string is a URL
    // @param string $url
    // @return bool
    function isURL($url = NULL) {
        if($url==NULL) return false;
    
        $protocol = '(http://|https://)';
        $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
    
        $regex = "^". $protocol . // must include the protocol
                 '(' . $allowed . '{1,63}\.)+'. // 1 or several sub domains with a max of 63 chars
                 '[a-z]' . '{2,6}'; // followed by a TLD
        if(eregi($regex, $url)==true) return true;
        else return false;
    }
    
  11. ==============================

    11.

    function is_valid_url ($url="") {
    
            if ($url=="") {
                $url=$this->url;
            }
    
            $url = @parse_url($url);
    
            if ( ! $url) {
    
    
                return false;
            }
    
            $url = array_map('trim', $url);
            $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
            $path = (isset($url['path'])) ? $url['path'] : '';
    
            if ($path == '') {
                $path = '/';
            }
    
            $path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';
    
    
    
            if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) ) {
                if ( PHP_VERSION >= 5 ) {
                    $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
                }
                else {
                    $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
    
                    if ( ! $fp ) {
                        return false;
                    }
                    fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
                    $headers = fread ( $fp, 128 );
                    fclose ( $fp );
                }
                $headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
                return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
            }
    
            return false;
        }
    
  12. ==============================

    12.

    .NET StackOverflow 질문 및이 질문에서 참조한이 기사에는이 URI 유효성 검사기 (URI는 URL과 URN의 유효성을 검사한다는 의미)가 있습니다.

    if( ! preg_match( "/^([a-z][a-z0-9+.-]*):(?:\\/\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\3)@)?(?=(\\[[0-9A-F:.]{2,}\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\5(?::(?=(\\d*))\\6)?)(\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*))\\8)?|(\\/?(?!\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*))\\10)?)(?:\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/?]|%[0-9A-F]{2})*))\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/?]|%[0-9A-F]{2})*))\\12)?$/i", $uri ) )
    {
        throw new \RuntimeException( "URI has not a valid format." );
    }
    

    성공적으로 Uri이라는 이름으로 만든 ValueObject 내부에서이 함수를 단위 테스트하고 UriTest에서 테스트했습니다.

    <?php
    
    declare( strict_types = 1 );
    
    namespace XaviMontero\ThrasherPortage\Tests\Tour;
    
    use XaviMontero\ThrasherPortage\Tour\Uri;
    
    class UriTest extends \PHPUnit_Framework_TestCase
    {
        private $sut;
    
        public function testCreationIsOfProperClassWhenUriIsValid()
        {
            $sut = new Uri( 'http://example.com' );
            $this->assertInstanceOf( 'XaviMontero\\ThrasherPortage\\Tour\\Uri', $sut );
        }
    
        /**
         * @dataProvider urlIsValidProvider
         * @dataProvider urnIsValidProvider
         */
        public function testGetUriAsStringWhenUriIsValid( string $uri )
        {
            $sut = new Uri( $uri );
            $actual = $sut->getUriAsString();
    
            $this->assertInternalType( 'string', $actual );
            $this->assertEquals( $uri, $actual );
        }
    
        public function urlIsValidProvider()
        {
            return
                [
                    [ 'http://example-server' ],
                    [ 'http://example.com' ],
                    [ 'http://example.com/' ],
                    [ 'http://subdomain.example.com/path/?parameter1=value1&parameter2=value2' ],
                    [ 'random-protocol://example.com' ],
                    [ 'http://example.com:80' ],
                    [ 'http://example.com?no-path-separator' ],
                    [ 'http://example.com/pa%20th/' ],
                    [ 'ftp://example.org/resource.txt' ],
                    [ 'file://../../../relative/path/needs/protocol/resource.txt' ],
                    [ 'http://example.com/#one-fragment' ],
                    [ 'http://example.edu:8080#one-fragment' ],
                ];
        }
    
        public function urnIsValidProvider()
        {
            return
                [
                    [ 'urn:isbn:0-486-27557-4' ],
                    [ 'urn:example:mammal:monotreme:echidna' ],
                    [ 'urn:mpeg:mpeg7:schema:2001' ],
                    [ 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],
                    [ 'rare-urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66' ],
                    [ 'urn:FOO:a123,456' ]
                ];
        }
    
        /**
         * @dataProvider urlIsNotValidProvider
         * @dataProvider urnIsNotValidProvider
         */
        public function testCreationThrowsExceptionWhenUriIsNotValid( string $uri )
        {
            $this->expectException( 'RuntimeException' );
            $this->sut = new Uri( $uri );
        }
    
        public function urlIsNotValidProvider()
        {
            return
                [
                    [ 'only-text' ],
                    [ 'http//missing.colon.example.com/path/?parameter1=value1&parameter2=value2' ],
                    [ 'missing.protocol.example.com/path/' ],
                    [ 'http://example.com\\bad-separator' ],
                    [ 'http://example.com|bad-separator' ],
                    [ 'ht tp://example.com' ],
                    [ 'http://exampl e.com' ],
                    [ 'http://example.com/pa th/' ],
                    [ '../../../relative/path/needs/protocol/resource.txt' ],
                    [ 'http://example.com/#two-fragments#not-allowed' ],
                    [ 'http://example.edu:portMustBeANumber#one-fragment' ],
                ];
        }
    
        public function urnIsNotValidProvider()
        {
            return
                [
                    [ 'urn:mpeg:mpeg7:sch ema:2001' ],
                    [ 'urn|mpeg:mpeg7:schema:2001' ],
                    [ 'urn?mpeg:mpeg7:schema:2001' ],
                    [ 'urn%mpeg:mpeg7:schema:2001' ],
                    [ 'urn#mpeg:mpeg7:schema:2001' ],
                ];
        }
    }
    
    <?php
    
    declare( strict_types = 1 );
    
    namespace XaviMontero\ThrasherPortage\Tour;
    
    class Uri
    {
        /** @var string */
        private $uri;
    
        public function __construct( string $uri )
        {
            $this->assertUriIsCorrect( $uri );
            $this->uri = $uri;
        }
    
        public function getUriAsString()
        {
            return $this->uri;
        }
    
        private function assertUriIsCorrect( string $uri )
        {
            // https://stackoverflow.com/questions/30847/regex-to-validate-uris
            // http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/
    
            if( ! preg_match( "/^([a-z][a-z0-9+.-]*):(?:\\/\\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\\3)@)?(?=(\\[[0-9A-F:.]{2,}\\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\\5(?::(?=(\\d*))\\6)?)(\\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*))\\8)?|(\\/?(?!\\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*))\\10)?)(?:\\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/?]|%[0-9A-F]{2})*))\\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@\\/?]|%[0-9A-F]{2})*))\\12)?$/i", $uri ) )
            {
                throw new \RuntimeException( "URI has not a valid format." );
            }
        }
    }
    

    46 개의 테스트에서 65 개의 어설 션이 있습니다. 주의 : 유효한 데이터 공급자 2 개와 잘못된 식 2 개가 있습니다. 하나는 URL 용이고 다른 하나는 URN 용입니다. v5.6 * 또는 그 이전 버전의 PhpUnit을 사용하는 경우 두 데이터 공급자를 하나의 단일 공급자로 조인해야합니다.

    xavi@bromo:~/custom_www/hello-trip/mutant-migrant$ vendor/bin/phpunit
    PHPUnit 5.7.3 by Sebastian Bergmann and contributors.
    
    ..............................................                    46 / 46 (100%)
    
    Time: 82 ms, Memory: 4.00MB
    
    OK (46 tests, 65 assertions)
    

    이 샘플 URI 검사기에는 100 %의 코드 커버리지가 있습니다.

  13. ==============================

    13.

    피터의 정규 표현은 여러 가지 이유에서 나에게 적합하지 않습니다. 그것은 도메인 이름에있는 모든 종류의 특수 문자를 허용하고 많이 테스트하지 않습니다.

    Frankie의 함수는 나에게 잘 어울리고 함수를 원하지 않으면 컴포넌트에서 좋은 정규 표현식을 만들 수있다.

    ^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}
    

    테스트되지는 않았지만 작동해야한다고 생각합니다.

    또한 Owen의 대답도 100 % 보지 않습니다. 정규 표현식의 도메인 부분을 가져 와서 Regex 테스터 도구 (http://erik.eae.net/playground/regexp/regexp.html)에서 테스트했습니다.

    나는 다음 줄을 넣는다.

    (\S*?\.\S*?)
    

    "정규 표현식"섹션에서 및 다음 행 :

    "샘플 텍스트"섹션에서

    그 결과 마이너스 문자가 통과되었습니다. \ S는 공백이 아닌 문자를 의미하기 때문입니다.

    Frankie의 정규 표현식은 첫 문자에 대해이 부분을 가지고 있기 때문에 빼기를 처리합니다.

    [a-z0-9]
    

    마이너스 또는 다른 특수 문자를 허용하지 않습니다.

  14. ==============================

    14.

    내가 그랬던 것처럼 여기있다. 하지만 나는 정규 표현식에 대해 그렇게 확신하지 않는다고 언급하고 싶다. 그러나 그것은 너를 일해야한다 :)

    $pattern = "#((http|https)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|”|\"|'|:|\<|$|\.\s)#i";
            $text = preg_replace_callback($pattern,function($m){
                    return "<a href=\"$m[1]\" target=\"_blank\">$m[1]</a>$m[4]";
                },
                $text);
    

    이렇게하면 패턴에 평가 마커가 필요하지 않습니다.

    희망이 도움이 :)

  15. ==============================

    15.

    좋아요, 그래서 이것은 간단한 정규 표현식보다 조금 더 복잡합니다. 그러나 그것은 다른 유형의 URL을 허용합니다.

    예 :

    유효한 것으로 표시되어야하는 모든 것.

    function is_valid_url($url) {
        // First check: is the url just a domain name? (allow a slash at the end)
        $_domain_regex = "|^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})/?$|";
        if (preg_match($_domain_regex, $url)) {
            return true;
        }
    
        // Second: Check if it's a url with a scheme and all
        $_regex = '#^([a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))$#';
        if (preg_match($_regex, $url, $matches)) {
            // pull out the domain name, and make sure that the domain is valid.
            $_parts = parse_url($url);
            if (!in_array($_parts['scheme'], array( 'http', 'https' )))
                return false;
    
            // Check the domain using the regex, stops domains like "-example.com" passing through
            if (!preg_match($_domain_regex, $_parts['host']))
                return false;
    
            // This domain looks pretty valid. Only way to check it now is to download it!
            return true;
        }
    
        return false;
    }
    

    허용하려는 프로토콜에 대한 in_array 검사가 있습니다 (현재 해당 목록에 http 및 https 만 있음).

    var_dump(is_valid_url('google.com'));         // true
    var_dump(is_valid_url('google.com/'));        // true
    var_dump(is_valid_url('http://google.com'));  // true
    var_dump(is_valid_url('http://google.com/')); // true
    var_dump(is_valid_url('https://google.com')); // true
    
  16. ==============================

    16.

    다음은 RegEx를 사용하는 URL 유효성 검사를위한 간단한 클래스입니다. 그런 다음 널리 사용되는 RBL (Realtime Blackhole Lists) 서버와 도메인을 상호 참조합니다.

    설치 :

    require 'URLValidation.php';
    

    용법:

    require 'URLValidation.php';
    $urlVal = new UrlValidation(); //Create Object Instance
    

    domain () 메소드의 매개 변수로 URL을 추가하고 리턴을 확인하십시오.

    $urlArray = ['http://www.bokranzr.com/test.php?test=foo&test=dfdf', 'https://en-gb.facebook.com', 'https://www.google.com'];
    foreach ($urlArray as $k=>$v) {
    
        echo var_dump($urlVal->domain($v)) . ' URL: ' . $v . '<br>';
    
    }
    

    산출:

    bool(false) URL: http://www.bokranzr.com/test.php?test=foo&test=dfdf
    bool(true) URL: https://en-gb.facebook.com
    bool(true) URL: https://www.google.com
    

    위에서 볼 수 있듯이 www.bokranzr.com은 RBL을 통해 악성 웹 사이트로 표시되므로 도메인은 false로 반환됩니다.

  17. ==============================

    17.

    WordPress로 개발하는 사람은 그냥

    esc_url_raw($url) === $url
    

    URL의 유효성을 검사합니다 (여기에있는 esc_url_raw의 WordPress 문서). 그것은 유니 코드 및 XSS 안전이기 때문에 filter_var ($ url, FILTER_VALIDATE_URL)보다 훨씬 나은 URL을 처리합니다. (여기에는 filter_var의 모든 문제점을 언급하는 좋은 기사가 있습니다).

  18. ==============================

    18.

    이 URL이 일치하는 데 가장 유용하다는 것을 알았습니다.

    ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
    
  19. ==============================

    19.

    거기에 PHP 네이티브 함수가 있습니다 :

    $url = 'http://www.yoururl.co.uk/sub1/sub2/?param=1&param2/';
    
    if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
        // Wrong
    }
    else {
        // Valid
    }
    

    필터링 된 데이터를 반환하거나 필터가 실패하면 FALSE를 반환합니다.

    그것을 여기에서 확인해라.

  20. ==============================

    20.

    "/(http(s?):\/\/)([a-z0-9\-]+\.)+[a-z]{2,4}(\.[a-z]{2,4})*(\/[^ ]+)*/i"
    

    참고 : 나쁜 영어로 죄송합니다. 우리 나라는 그것을 잘 사용하지 않습니다.

  21. from https://stackoverflow.com/questions/206059/php-validation-regex-for-url by cc-by-sa and MIT lisence