3v4l.org

run code in 300+ PHP versions simultaneously
<?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'; });

preferences:
32.49 ms | 402 KiB | 5 Q