Last active
June 20, 2017 19:14
-
-
Save kodie/1ef232a8169413359f23005c420c21be to your computer and use it in GitHub Desktop.
Add, change or remove a parameter from a URL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function change_url_param($params = null, $url = null) { | |
if (!$url) { $url = '//' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; } | |
$p = parse_url($url); | |
if (isset($p['scheme'])) { $s = $p['scheme'] . '://'; } else { $s = '//'; } | |
if (substr($url, 0, 2) == '//') { $s = '//'; } | |
if (isset($p['host'])) { $h = $p['host']; } else { $h = ''; } | |
if (isset($p['path'])) { $t = $p['path']; } else { $t = '/'; } | |
if (isset($p['query'])) { parse_str($p['query'], $q); } else { $q = array(); } | |
if (isset($p['fragment'])) { $f = '#' . $p['fragment']; } else { $f = ''; } | |
if (gettype($params) === 'NULL') { $q = ''; } | |
if (gettype($params) === 'string') { $params = array($params => null); } | |
if (gettype($params) === 'array') { $q = http_build_query(array_filter(array_merge($q, $params), create_function('$a', 'return $a!==null;'))); } | |
if ($q) { $q = '?' . $q; } | |
$n = $s . $h . $t . $q . $f; | |
return $n; | |
} | |
$url = 'http://example.com/?page=1&count=10&order=asc#top'; | |
echo change_url_param(array(), $url) . "\n"; | |
echo change_url_param(null, $url) . "\n"; | |
echo change_url_param('count', $url) . "\n"; | |
echo change_url_param(array('page'=>2), $url) . "\n"; | |
echo change_url_param(array('order'=>null), $url) . "\n"; | |
echo change_url_param(array('count'=>20), $url) . "\n"; | |
echo change_url_param(array('view'=>'grid'), $url) . "\n"; | |
echo change_url_param(array('count'=>50,'page'=>2,'view'=>'list'), $url) . "\n"; | |
/* Output: | |
http://example.com/?page=1&count=10&order=asc#top | |
http://example.com/#top | |
http://example.com/?page=1&order=asc#top | |
http://example.com/?page=2&count=10&order=asc#top | |
http://example.com/?page=1&count=10#top | |
http://example.com/?page=1&count=20&order=asc#top | |
http://example.com/?page=1&count=10&order=asc&view=grid#top | |
http://example.com/?page=2&count=50&order=asc&view=list#top | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment