wp_parse_url and wp_parse_str

Advertisement

wp_parse_url() wp_parse_url()

wp_parse_url() is wrapper function for PHP’s parse_url() function that handles consistency in the return values across PHP versions.

Example 1: Example 1:

Let’s extract the scheme, host, and path from the URL https://maheshwaghmare.com/ by using the wp_parse_url().

$url_parse = wp_parse_url( 'https://maheshwaghmare.com/' );
var_dump( $url_parse );

The output of the above code is below:

array (size=3)
   'scheme' => string 'https' (length=5)
   'host' => string 'maheshwaghmare.com' (length=18)
   'path' => string '/' (length=1)

Here, we can see that the function returns the scheme, host, and path of the URL.

Let’s check another example that contains the query parameters.

Top ↑

Example 2: Example 2:

If we have a query parameters in the URL then the function wp_parse_url() return additional query parameter. E.g.

$url_parse = wp_parse_url( 'https://maheshwaghmare.com/?s=cli&one=1&two=2&three=3' );
var_dump( $url_parse );

Output

array (size=4)
   'scheme' => string 'https' (length=5)
   'host' => string 'maheshwaghmare.com' (length=18)
   'path' => string '/' (length=1)
   'query' => string 's=cli&one=1&two=2&three=3' (length=25)

Here, We can see that the query parameter contains the value s=cli&one=1&two=2&three=3.

Note its time to use function wp_parse_str().

Top ↑

wp_parse_str() wp_parse_str()

The function wp_parse_str() is a wrapper function of PHP parse_str() function.

$url_parse = wp_parse_url( 'https://maheshwaghmare.com/?s=cli&one=1&two=2&three=3' );
wp_parse_str( $url_parse['query'], $args );
var_dump( $args );

Output

array (size=4)
   's' => string 'cli' (length=3)
   'one' => string '1' (length=1)
   'two' => string '2' (length=1)
   'three' => string '3' (length=1)

How to use the wp_parse_url() and wp_parse_str() functions in WordPress.

Leave a Reply