Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of parsing URL by PHP

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the methods of PHP parsing URL". In daily operation, I believe many people have doubts about the method of PHP parsing URL. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what are the methods of PHP parsing URL?" Next, please follow the editor to study!

There are two methods in PHP that can be used to parse URL, which are parse_url and parse_str.

Parse_url

Parse the URL and 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 verify the validity of a given URL, but to decompose it into the parts listed below. Incomplete URL is also accepted, and parse_url () will try to parse it as correctly as possible.

Parameters.

The URL to be parsed by url. Invalid characters will be replaced with _.

Component specifies one of 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 to get the string of the specified part of the URL. (except when specified as PHP_URL_PORT, a value of integer is returned.)

Return value

FALSE may be returned for seriously unqualified URL,parse_url ().

If the component parameter is omitted, an associative array array is returned, in which at least one element is currently present. There are several possible keys in the array:

Scheme-such as http

Host

Port

User

Pass

Path

Query-in the question mark? After that

Fragment-after the hash symbol #

If the component parameter is specified, parse_url () returns a string (or an integer when specified as PHP_URL_PORT) instead of array. If the specified component in URL does not exist, NULL is returned.

Example

The copy code is as follows:

The above routine outputs:

The copy code is as follows:

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 the query string (query string) passed in by URL, it is parsed to a variable and set 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 arr is set, the variable will be stored in the array as an array element instead. 、

Example

The copy code is as follows:

Some time ago, when I was reading the source code of php-resque, I saw the application of these two methods in it. I felt that I used it very well to parse the settings of redis links.

The format of the redis link is: redis://user:pass@host:port/db?option1=val1&option2=val2, is it the same as URL, so it is easy to parse with the above two methods.

Address: https://github.com/chrisboulton/php-resque/blob/master/lib/Resque/Redis.php

The code is as follows:

The copy code is as follows:

/ * *

* Parse a DSN string, which can have one of the following formats:

*

*-host:port

*-redis://user: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 is not used.

*

* @ param string $dsn A DSN string

* @ return array An array of DSN compotnents, with 'false' values for any unknown 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::DEFAULT_HOST

}

$parts = parse_url ($dsn)

/ / Check the URI scheme

$validSchemes = array ('redis',' tcp')

If (isset ($parts ['scheme']) & &! In_array ($parts ['scheme'], $validSchemes)) {

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'])) {

$parts ['host'] = $parts [' path']

Unset ($parts ['path'])

}

/ / Extract the port number as an integer

$port = isset ($parts ['port'])? Intval ($parts ['port']): self::DEFAULT_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

);

}

At this point, the study of "what are the methods of PHP parsing URL" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report