電気ひつじ牧場

技術メモ

【PHP】URIから画像ファイル名を取り出す

正規表現でシュッとやるとスマートですね。

function myurlmatch($url){
    preg_match('/.*\/(.*)\.(png|jpg|jpeg|gif|)$/i', $url, $match);
    return $match[1] ?? null;
}

拡張子を除いた画像ファイル名(png, jpg, gif)のみ取り出します。iオプションのお陰で拡張子が大文字でもマッチします。

試してみる

$a = myurlmatch("https://example.com/hoge.JPG");
$b = myurlmatch("http://example.com/foo/bar/hoge.png");
$c = myurlmatch("http://example.com/2018.11.13foo_bar.GIF");
$d = myurlmatch("https://example.com/hoge.pdf");

結果

$a = "hoge"
$b = "hoge"
$c = "2018.11.13foo_bar"
$d = null