Learning PHP--parsing URLs

Source: Internet
Author: User
Tags format array copy integer parse string string variable port number
There are two methods in PHP that can be used to parse URLs, respectively, Parse_url and Parse_str.   parse_url resolves the URL and returns its component   mixed Parse_url (string $url [, int $component =-1])   This function resolves a URL and returns an association Array that contains the various components that appear in the URL.   This function is not used to verify the legality of a given URL, but to decompose it into the sections listed below. An incomplete URL is also accepted, and Parse_url () tries to parse it as correctly as possible.   parameters   URL   URL to resolve. Invalid characters will be replaced with _.   Component   designation Php_url_scheme, Php_url_host, Php_url_port, Php_url_user, Php_url_pass, Php_url_path, Php_url One of the _query or php_url_fragment to get a string of the part specified in the URL. (An integer value is returned, except when specified as Php_url_port.)   return value   for severely unqualified url,parse_url () may return FALSE.   If component argument is omitted, an associative array array is returned, and at least one element is currently in the array. There are several possible keys in the array:   scheme-such as HTTP host port user Pass path query-in the question mark? After fragment-after the hash symbol # If the component argument is specified, Parse_url () returns a string (or returns an integer when specified as Php_url_port) instead of an array. If the component specified in the URL does not exist, NULL will be returned.   example   <?php $url = ' http://username:password@hostname/path?arg=value#anchor '; Print_r (Parse_url ($url)); Echo Parse_url ($url, Php_url_path);?>  the above routines will output:   Copy code Array (    [scheme] => http     [host] => hostname     [user] => username     [pass] => password     [path] =>/path &N Bsp   [query] => arg=value     [fragment] => anchor)/path Copy code Parse_str parse string into multiple variables   void Parse_ STR (string $str [, Array & $arr])   If STR is the query string that is passed in by the URL, parse it into a variable and set to the current scope.   Get the current query_string, you can use the $_server[' query_string ' variable.   Parameters   str   the input string.   ARR   If you set the second variable arr, the variable will be stored as an array element in the array as an alternative. ,   instance   copy code <?php $STR = "First=value&arr[]=foo+bar&arr[]=baz"; Parse_str ($STR); Echo $first;  //value echo $arr [0]; Foo bar echo $arr [1]; Baz Parse_str ($STR, $output); echo $output [' a '];  //value echo $output [' arr '][0]; Foo bar echo $output [' arr '][1]; Baz?>  copy code     some time before reading the source of Php-resque, saw in which the two sides of theThe application of the method, the feeling is very good, used to resolve the Redis link settings.   Redis link format is: Redis://user:pass@host:port/db?option1=val1&option2=val2, is not the same as the URL, so the above two methods are easy to parse.   Address: https://github.com/chrisboulton/php-resque/blob/master/lib/Resque/Redis.php   Code is as follows:   Copy code    /**      * Parse a DSN string, which can have one of the following formats:     &NB sp;*      *-host:port      *-redis://user:pass@host:port/db?option1=val1&option2= Val2      *-tcp://user:pass@host:port/db?option1=val1&option2=val2      *   & nbsp  * note:the ' user ' part of the DSN is not used.      *      * @param string $dsn A DSN string      * @return array an array o F DSN compotnents, with ' false ' values for any unknown components. e.g.      *               [host, port, DB, User, pass, options]   & nbsp  */  &NBsp public static function Parsedsn ($DSN)     {        if ($dsn = = ") {      & nbsp    //Use a sensible default for a empty DNS string             $DSN = ' redis:// ' . Self::D efault_host;        }         $parts = Parse_url ($DSN);        //Check the URI scheme         $validSchemes = Array (' Redis ', ' TCP ');         if (Isset ($parts [' Scheme ']) &&! In_array ($parts [' scheme '], $validSchemes)] {  & nbsp         throw new \invalidargumentexception ("Invalid DSN". Supported schemes are ". Implode (', ', $validSchemes));        }        //Allow simple ' hostname ' format, which ' Parse_url ' treats as a Path, not host.         if (! isset ($parts [' Host ']) && isset ($parts [' path '])] {      &NBsp     $parts [' host '] = $parts [' path '];             unset ($parts [' path ']);        }        //Extract the port number as an integer       &N Bsp $port = Isset ($parts [' Port '])? Intval ($parts [' Port ']): self::D efault_port;        //Get the database from the ' path ' part of the URI         $database = FA Lse         if (Isset ($parts [' path ']) {           //Strip Non-digit Char s from path             $database = intval (preg_replace ('/[^0-9]/', ', $parts [' path ']);        }        //Extract any ' user ' and ' pass ' values       &NB Sp $user = Isset ($parts [' user '])? $parts [' User ']: false;         $pass = isset ($parts [' Pass '])? $parts [' Pass ']: false;        //Convert the QUery string into a associative array         $options = array ();         if (Isset ($parts [' query '])] {           //Parse the query str ing into an array             PARSE_STR ($parts [' query '], $options);        }         return Array (            $parts [' Host '],             $port,             $database,   &nbsp ;         $user,             $pass,           &NB Sp $options,        );    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.