Home  >  Article  >  Backend Development  >  How to use php parse_url() function

How to use php parse_url() function

青灯夜游
青灯夜游Original
2021-07-15 10:43:392721browse

parse_url() is a built-in function in PHP, mainly used to parse URLs and return their components. The syntax format is "parse_url($url,$component=-1)"; this function parses a URL and Returns an associative array containing the various components of the URL.

How to use php parse_url() function

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

The parse_url() function is a built-in function in PHP Function used to return the component of the url by parsing it. It parses a URL and returns an associative array containing its individual components.

Syntax format:

parse_url($url, $component = -1)
  • url: URL to be parsed. Invalid characters will be replaced with _.

  • component:

    Specify 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, an integer value will be returned).

Return value:

  • For severely unqualified URLs, parse_url() may return false.

  • If the component parameter is omitted, an associative array array will be returned, and at least one element will currently be in the array. Possible keys in the array are the following:

    • scheme - such as http

    • host

    • port

    • user

    • pass

    • ##path

    • query - after the question mark?

    • fragment - after the hash symbol

  • #if specified component parameter, parse_url() returns a string (or an integer when specified as PHP_URL_PORT) instead of an array. If the specified component in the URL does not exist, null will be returned.

Example:


<?php
$url = &#39;http://username:password@hostname/path?arg=value#anchor&#39;;

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

Output:


Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path

Note:

parse_url() is specially used to parse URLs instead of URIs. However, there is an exception to comply with PHP backwards compatibility needs, which allows three slashes (file:///...) for the file:// protocol. No other agreement can do this.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to use php parse_url() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn