【PHP】URLからパラメータを全て削除する方法

strtok()

?で分割。


$url = 'https://example.com/?test=123';
$url = strtok($url, '?');
echo $url; // https://example.com/

explode()

?で区切って配列にしてから取り出す。


$url = 'https://example.com/?test=123';
$url = explode('?', $url);
echo $url[0]; // https://example.com/

preg_replace()

正規表現で?以降を空文字で置換削除。


$url = 'https://example.com/?test=123';
$url = preg_replace('/\?.+$/', '', $url);
echo $url; // https://example.com/

parse_url()

URLを一旦パースしてからパラメータ以外を結合。


$url = 'https://example.com/?test=123';
$url = parse_url($url);
$url = $url['scheme'].'://'.$url['host'].$url['path'];
echo $url; // https://example.com/

preg_match()

正規表現で?より前の部分を取り出す。


$url = 'https://example.com/?test=123';
preg_match('/(.+)\?/', $url, $matches);
echo $matches[1]; // https://example.com/

速度ランキング

上記のコードを100万回ループさせた場合の処理時間です。

1位strtok()0.567 seconds
2位explode()0.578 seconds
3位preg_replace()0.608 seconds
4位parse_url()0.684 seconds
5位preg_match()0.801 seconds

まとめ

strtok()が短く書ける上に速度も速いのでオススメ。