wp_parse_url

A wrapper for PHP's parse_url() function that handles consistency in the return values across PHP versions.

Description

wp_parse_url( (string) $url, (int) $component = -1 ); 

PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including schemeless and relative url's with :// in the path. This function works around those limitations providing a standard output on PHP 5.2~5.4+.

Secondly, across various PHP versions, schemeless URLs starting containing a : in the query are being handled inconsistently. This function works around those differences as well.

Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated when URL parsing failed.

Parameters (2)

0. $url (string)
The URL to parse.
1. $component — Optional. (int) => -1
The specific component to retrieve. Use one of the PHP predefined constants to specify which one. Defaults to -1 (= return all parts as an array). @see http://php.net/manual/en/function.parse-url.php

Usage

  1. if ( !function_exists( 'wp_parse_url' ) ) { 
  2. require_once ABSPATH . WPINC . '/http.php'; 
  3.  
  4. // The URL to parse. 
  5. $url = ''; 
  6. $component = -1; 
  7.  
  8. // NOTICE! Understand what this does before running. 
  9. $result = wp_parse_url($url, $component); 
  10.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/http.php  
  1. function wp_parse_url( $url, $component = -1 ) { 
  2. $to_unset = array(); 
  3. $url = strval( $url ); 
  4.  
  5. if ( '//' === substr( $url, 0, 2 ) ) { 
  6. $to_unset[] = 'scheme'; 
  7. $url = 'placeholder:' . $url; 
  8. } elseif ( '/' === substr( $url, 0, 1 ) ) { 
  9. $to_unset[] = 'scheme'; 
  10. $to_unset[] = 'host'; 
  11. $url = 'placeholder://placeholder' . $url; 
  12.  
  13. $parts = @parse_url( $url ); 
  14.  
  15. if ( false === $parts ) { 
  16. // Parsing failure. 
  17. return $parts; 
  18.  
  19. // Remove the placeholder values. 
  20. foreach ( $to_unset as $key ) { 
  21. unset( $parts[ $key ] ); 
  22.  
  23. return _get_component_from_parsed_url_array( $parts, $component );