Discussion on PHP parsing URL function parse_url and parse_str

Source: Internet
Author: User

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 components

Mixed Parse_url (string $url [, int $component =-1])


This function resolves a URL and returns an associative array containing 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

The URL to parse for the URL. Invalid characters will be replaced with _.

component Specifies Php_url_scheme, Php_url_host, Php_url_port, Php_url_user, Php_url_pass, Php_url_path, Php_url_query, or PHP_U One of the rl_fragment to get a string for the part specified in the URL. (An integer value is returned, except when specified as Php_url_port.)

return value

The severely unqualified url,parse_url () may return FALSE.

If the 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-at question mark? After
Fragment-After the hash symbol #
If the component parameter 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.

Instance

<?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:
Array
(
    [scheme] => HTTP
    [host] => hostname
    [user] => username
    [Pass] => password
    [path] =>/path
    [query] => arg=value
    [fragment] => anchor
)
/path

Parse_str

Parse a string into multiple variables

void Parse_str (String $str [, Array & $arr])
If STR is a query string that is passed in by a URL, it resolves to a variable and sets it to the current scope.

To get the current query_string, you can use the $_server[' query_string ' variable.

Parameters

The string entered by Str.

Arr If you set the second variable arr, the variable will be stored as an array element in the array as an alternative. 、

Instance

<?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
Some time ago in reading Php-resque source code, saw in which the two methods of application, feel 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

The code is as follows:

/** * Parse a DSN string, which can have one of the following formats: * *-host:port *-Redis://use
     R:pass@host:port/db?option1=val1&option2=val2 *-Tcp://user:pass@host:port/db?option1=val1&option2=val2
     * * note:the ' user ' part of the DSN isn't used. * * @param string $DSN A DSN String * @return array an array of DSN compotnents, with ' false ' to any UNK Nown components.
     e.g. * [Host, port, DB, User, pass, Options] */public static function Parsedsn ($DSN) {if ( $dsn = = ') {//Use a sensible default for an 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)) {throw new \invalidargume Ntexception ("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 ']) {$parts [' host '] = $parts [' path '];
        unset ($parts [' path ']); }//Extract the port number as an integer $port = isset ($parts [' Port '])?
        Intval ($parts [' Port ']): self::D efault_port;
        Get the "database from" the ' path ' part of the URI $database = false; if (Isset ($parts [' path '])) {//Strip Non-digit chars from Path $database = Intval (Preg_replace ('/
        [^0-9]/', ', $parts [' path ']]); }//Extract any ' user ' and ' pass ' values $user = isset ($parts [' user '])?
        $parts [' User ']: false; $pass = Isset ($parts [' Pass '])?
        $parts [' Pass ']: false;
        Convert the query string into an associative array $options = array ();
 if (Isset ($parts [' query '])) {           Parse the query string into an array parse_str ($parts [' query '], $options);
            return Array ($parts [' Host '], $port, $database, $user,
    $pass, $options,); }

The above is personal about PHP parse URL function parse_url and parse_str understanding, here record down, share to everybody, hope to help small partner


Article Source: http://www.daimajiayuan.com/course/php/21917.html

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.