parse_url

The parse_url function parses a URL and returns its components. The function breaks up a URL into different URL parts that exist in the passed URL. The values are not URL decoded and the function does not validate the URL. 

The values returned can include:

  • scheme - also known as the protocol - e.g. http or https
  • host - the combination of the domain name and subdomain(s)
  • port - the port number
  • user - only returned if a username is part of the URL
  • pass - only returned if a password is part of the URL 
  • path - the value after the host/domain name starting with the "/"
  • query - the value after the question mark ?
  • fragment - the value after the hash mark #
  • domain - the domain name
  • subdomain - the subdomain if specified. "www" is a common value
  • subdomains - an array of all possible subdomains
  • suffix - the top-level domain (TLD) and second-level domain (SLD) if it exists

Only the values that actually exist in the URL will be returned. 

If the value passed is not a valid URL and it cannot be parsed then false is returned.

If only a specific URL part is required then that can be passed as the second parameter. If it exists in the URL then it will be returned. Otherwise false will be returned.

Example

{% set url = 'https://www.branchcms.com/support' %}
{% set urlParts = parse_url(url) %}

{# The above example will return #}

array (
    'scheme' => 'https',
    'host' => 'www.branchcms.com',
    'path' => '/support'
    'domain' => 'branchcms.com',
    'subdomain' => 'www',
    'subdomains' => array('www')
    'suffix' => 'com'
)

{# Combine with the URL filter to ensure a valid URL #}

{% set urlParts = parse_url(myUrl|url) %}

Arguments

The parse_url function has the following signature.

parse_url(url, part)

Arguments Description
url

The URL value to parse.

part

The single URL part to return. If the part exists in the URL then it will be returned. Otherwise false is returned.

If the part exists in the URL then the value returned is a string. The exception is "port" where an integer is returned.

Valid part values are:

  • scheme
  • host
  • port
  • user
  • pass
  • path
  • query
  • fragment
  • domain
  • subdomain
  • suffix

< Back to the list of functions