3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Response { public function __construct(protected $targetUrl = ''){} public function getTargetUrl(): string { return $this->targetUrl; } public function setTargetUrl(string $target_url): void { $this->targetUrl = $target_url; } } $withQuery = new Response('https://example.com?foo=bar'); $withoutQuery = new Response('https://example.com?'); $withoutQuestion = new Response('https://example.com'); function queryManip(Response $response): Response { // The 'destination' parameter should remain in the query but be // unused by the target_url. $target_url = $response->getTargetUrl(); if (str_contains($target_url, '?')) { $query_string = parse_url($target_url, PHP_URL_QUERY) ?: ''; parse_str($query_string, $query); $target_url = substr($target_url, 0, strpos($target_url, '?')) . '?' . http_build_query($query); } $response->setTargetUrl($target_url); return $response; } echo sprintf('With query: %s%s', queryManip($withQuery)->getTargetUrl(), \PHP_EOL); echo sprintf('Without query: %s%s', queryManip($withoutQuery)->getTargetUrl(), \PHP_EOL); echo sprintf('Without question: %s%s', queryManip($withoutQuestion)->getTargetUrl(), \PHP_EOL);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
With query: https://example.com?foo=bar Without query: https://example.com? Without question: https://example.com

preferences:
45.12 ms | 406 KiB | 5 Q