PHP 删除特定字符(文件扩展名)后的所有内容

PHP Remove anything after specific characters (file extensions)

我想删除特定字符集(即文件类型/扩展名)之后的所有内容。我已经尝试了很多在网上找到的脚本,但 none 确实能够满足我的需要,它们要么也删除文件扩展名,要么保留后面的部分参数。

$urls = array(
'http://www.example.com/images/image1.jpg',
'http://www.example.com/images/image2.png?arg=value',
'http://www.example.com/images/image3.jpg?foo=bar',
'http://www.example.com/images/image4.gif?v=1',
'http://www.example.com/images/image5.bmp?x=y',
'http://www.example.com/images/image6.tiff?werdfs=234234'
);

期望的结果:

http://www.example.com/images/image1.jpg
http://www.example.com/images/image2.png
http://www.example.com/images/image3.jpg
http://www.example.com/images/image4.gif
http://www.example.com/images/image5.bmp
http://www.example.com/images/image6.tiff

PHP 的 parse_url() 和 basename 怎么样?

$inName = $urls[0]; // for example
$newName = parse_url($inName,PHP_URL_SCHEME)
         . parse_url($inName,PHP_URL_HOST)
         . parse_url($inName,PHP_URL_PATH)
         . basename($inName);

也许这个对你有帮助。


$re = '/^.*(?:\.)[a-zA-Z]+/m';
$urls = array(
'http://www.example.com/images/image1.jpg',
'http://www.example.com/images/image2.png?arg=value',
'http://www.example.com/images/image3.jpg?foo=bar',
'http://www.example.com/images/image4.gif?v=1',
'http://www.example.com/images/image5.bmp?x=y',
'http://www.example.com/images/image6.tiff?werdfs=234234',
'asdasd'
);

foreach ($urls as $url) {
    preg_match($re, $url, $matches);
    if ($matches) {
        echo $matches[0];
        echo "\n";
    }
}

输出

http://www.example.com/images/image1.jpg
http://www.example.com/images/image2.png
http://www.example.com/images/image3.jpg
http://www.example.com/images/image4.gif
http://www.example.com/images/image5.bmp
http://www.example.com/images/image6.tiff