Last active
December 22, 2015 23:39
-
-
Save DaveRandom/6547976 to your computer and use it in GitHub Desktop.
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 | |
// Because PHP_URL_* constants are sequential :-( | |
const URL_SCHEME = 0x01; | |
const URL_USER = 0x02; | |
const URL_PASS = 0x04; | |
const URL_HOST = 0x08; | |
const URL_PORT = 0x10; | |
const URL_PATH = 0x20; | |
const URL_QUERY = 0x40; | |
const URL_FRAGMENT = 0x80; | |
function url_replace($url, $components, callable $callback) | |
{ | |
$map = [ | |
URL_SCHEME => 'scheme', | |
URL_USER => 'user', | |
URL_PASS => 'pass', | |
URL_HOST => 'host', | |
URL_PORT => 'port', | |
URL_PATH => 'path', | |
URL_QUERY => 'query', | |
URL_FRAGMENT => 'fragment', | |
]; | |
if (!$parts = parse_url($url)) { | |
return $url; | |
} | |
foreach ($map as $component => $key) { | |
if ($components & $component) { | |
$parts[$key] = $callback($parts[$key], $component); | |
} | |
} | |
$result = ''; | |
if (isset($parts['scheme'])) { | |
$result = $parts['scheme'] . ':'; | |
} | |
if (isset($parts['host'])) { | |
$result .= '//'; | |
if (isset($parts['user'])) { | |
$result .= $parts['user']; | |
if (isset($parts['pass'])) { | |
$result .= ':' . $parts['pass']; | |
} | |
$result .= '@'; | |
} | |
$result .= $parts['host']; | |
if (isset($parts['port'])) { | |
$result .= ':' . $parts['port']; | |
} | |
} | |
if (isset($parts['path'])) { | |
$result .= $parts['path']; | |
} | |
if (isset($parts['query'])) { | |
$result .= '?' . $parts['query']; | |
} | |
if (isset($parts['fragment'])) { | |
$result .= '#' . $parts['fragment']; | |
} | |
return $result; | |
} | |
$url = 'http://test.com/test-one,two three?a=b#bla'; | |
echo url_replace($url, URL_PATH, function($path) { | |
return '/foobar'; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment