Created
January 3, 2019 09:57
-
-
Save BlaM/610ca9d200be8be3f66f51e1055680c4 to your computer and use it in GitHub Desktop.
Simple "add query" function that does not use parse_str()
This file contains hidden or 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 add_query($url, $params, $replace = false) { | |
$pu = parse_url($url); | |
foreach ($params as $k => $v) { | |
$np = $k . '=' . urlencode($v); | |
if ($replace && preg_match('/(^|&)' . $k . '=/', $pu['query'])) { | |
$pu['query'] = preg_replace('/(^|&)' . $k . '=([^&]*)?/', '$1' . str_replace('$', '\$', $np), $pu['query']); | |
} else { | |
$pu['query'] .= (empty($pu['query']) ? '' : '&') . $np; | |
} | |
} | |
if (strlen($pu['port']) > 0) $pu['port'] = ':' . $pu['port']; | |
if (strlen($pu['query']) > 0) $pu['query'] = '?' . $pu['query']; | |
if (strlen($pu['pass']) > 0) $pu['user'] .= ':' . $pu['pass']; | |
if (strlen($pu['user']) > 0) $pu['user'] .= '@'; | |
if (strlen($pu['fragment']) > 0) $pu['fragment'] = '#' . $pu['fragment']; | |
return $pu['scheme'] . '://' . $pu['user'] . $pu['host'] . $pu['port'] . $pu['path'] . $pu['query'] . $pu['fragment']; | |
} |
This file contains hidden or 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 | |
$url = 'http://www.example.com/test?test[]=1&stc=bla&test[]=2'; | |
// $url = 'http://www.example.com/test?2'; | |
echo add_query($url, array('stc' => 'hello'), true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment