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=3Changing one parameter of a link
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=3Functions used in this recipe
- parse_str — Parses a query string into an array.
- http_build_query — Builds a URL query string from an array.
- parse_url — Splits a URL into its parts.