<?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 = 'sip:foo@example.com';
echo url_replace($url, URL_PATH, function($path) {
return 'bar@example.com';
});
- Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- sip:bar@example.com
- Output for 5.3.0 - 5.3.29
- Parse error: syntax error, unexpected '[' in /in/9Fq0U on line 15
Process exited with code 255. - Output for 4.4.2 - 4.4.9, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17
- Parse error: syntax error, unexpected T_CONST in /in/0sjfI on line 4
Process exited with code 255. - Output for 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1, 5.0.0 - 5.0.5
- Parse error: parse error, unexpected T_CONST in /in/0sjfI on line 4
Process exited with code 255. - Output for 4.3.2 - 4.3.4
- Parse error: parse error in /in/0sjfI on line 4
Process exited with code 255. - Output for 4.3.0
- Parse error: parse error, unexpected T_CONST in /in/9Fq0U on line 4
Process exited with code 255.
preferences:
341.81 ms | 401 KiB | 460 Q