<?php
function url_replace($url, $component, callable $callback)
{
$map = [
PHP_URL_SCHEME => 2,
PHP_URL_HOST => 4,
PHP_URL_PATH => 5,
PHP_URL_QUERY => 7,
PHP_URL_FRAGMENT => 9,
];
if (!array_key_exists($component, $map)) {
return $url;
}
$index = $map[$component];
if (preg_match('~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~', $url, $matches, PREG_OFFSET_CAPTURE) && isset($matches[$index])) {
$tmp = call_user_func($callback, $matches[$index][0]);
return substr_replace($url, $tmp, $matches[$index][1], strlen($matches[$index][0]));
}
return $url;
}
$url = 'sip:foo@example.com';
echo url_replace($url, PHP_URL_PATH, function($path) {
return 'bar@example.com';
});
preferences:
47.04 ms | 402 KiB | 5 Q