Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to parse and build a query string

Short answer

parse_str() parses a string into an array, http_build_query() builds it back:

<?php
 
parse_str('q=php+book&page=2', $params);
 
echo json_encode($params), "\n";
echo http_build_query(['q' => 'php book', 'page' => 3]);

Output:

{"q":"php book","page":"2"}
q=php+book&page=3

Parse the link, change the value and build it again:

<?php
 
$url = 'https://example.com/search?q=php&page=2';
$parts = parse_url($url);
 
parse_str($parts['query'], $params);
$params['page'] = 3;
 
echo $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '?' . http_build_query($params);

Output:

https://example.com/search?q=php&page=3

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.