Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active November 24, 2015 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallacemaxters/8022c41d747322a75eba to your computer and use it in GitHub Desktop.
Save wallacemaxters/8022c41d747322a75eba to your computer and use it in GitHub Desktop.
Replace query string of url based on passed array
<?php
if (! function_exists('url_replace_query'))
{
function url_replace_query($url, array $parameters)
{
$parts = parse_url($url) + [
'scheme' => 'http',
'query' => NULL,
'path' => NULL,
];
if (! isset($parts['host'])) return false;
parse_str($parts['query'], $query);
$parameters += $query;
$newQueryString = http_build_query($parameters);
return $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '?' . $newQueryString;
}
}
@wallacemaxters
Copy link
Author

A little test:

$url = url_replace_query('http://teste.com.br/?test=1&name=Wallace',  ['name' => 'Miguel']);

echo $url; // http://teste.com.br/?test=1&name=Miguel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment