2 ways to parse URLs in PHP

Source: Internet
Author: User
Tags dsn
This article mainly introduces 2 methods of parsing URLs in PHP (Parse_url and PARSE_STR), as well as the introduction and usage of these 2 methods, which is very comprehensive and recommended to the small partners who need them.

There are two methods in PHP that can be used to parse URLs, namely Parse_url and PARSE_STR.

parse_url Parse URL, return its components

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

This function parses a URL and returns an associative array containing the various components that appear in the URL.

This function is not used to validate the legitimacy of a given URL, but to decompose it into the parts 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 Specify Php_url_scheme, Php_url_host, Php_url_port, Php_url_user, Php_url_pass, Php_url_path, Php_url_query, or PHP_ Url_fragment one of the strings that gets the specified part of the URL. (An integer value is returned, except when specified as Php_url_port).

return value

A url,parse_url () that is severely unqualified may return FALSE.

If the component parameter is omitted, an associative array array is returned, 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 question marks? After
Fragment-After 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

The code is as follows:

<?php$url = ' Http://username:password@hostname/path?arg=value#anchor ';p rint_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

Parsing a string into multiple variables

void Parse_str (String $str [, Array & $arr])

If STR is a query string that the URL passes in, 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 the second variable is set to ARR, the variable will be stored as an array element in the array as an alternative. 、

Instance

The code is as follows:

<?php$str = "First=value&arr[]=foo+bar&arr[]=baz";p arse_str ($STR); Echo $first;  Valueecho $arr [0]; Foo Barecho $arr [1]; Bazparse_str ($str, $output); Echo $output [' first '];  Valueecho $output [' arr '][0]; Foo barecho $output [' arr '][1]; Baz?>

A period of time before reading Php-resque source code, saw in which the two methods of application, feel good, used to parse Redis link settings.

The format of the Redis link is: Redis://user:pass@host:port/db?option1=val1&option2=val2, is not the same as the URL, so with 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://user:p     ASS@HOST:PORT/DB?OPTION1=VAL1&AMP;OPTION2=VAL2 *-Tcp://user:pass@host:port/db?option1=val1&option2=val2 *     * note:the ' user ' part of the DSN was not used. * * @param string $DSN A DSN String * @return array an array of DSN compotnents, with ' false ' values for any unkno WN components.     e.g.  * [Host, port, DB, User, pass, Options] */public static function Parsedsn ($DSN) {if ($dsn        = = ') {//Use a sensible the 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 \invalidargumen Texception ("Invalid DSN. Supported schemes is ". 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, $pa    SS, $options,); }

Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related Article

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.