php检查图像文件名结尾是不是.jpg,.jpeg,.png或.gif。

时间:2012-04-07 08:01:50

标签: php regex mime-types

我尝试将网页图片保存到本地,我在这里使用代码进行判断,如果图像文件名结尾不是.jpg,.jpeg,.png或.gif,请添加它们。我使用stripos,但是当像这样的图像网址时我遇到了一些麻烦。那怎么解决?谢谢。

$webimage = 'http://pcdn.500px.net/5953805/d0dd841969187f47e8ad9157713949b4b95b3bda/4.jpg?1333782904356';
$pieces = explode("/", $webimage); 
$pathend = end($pieces);
$imageinfo = @getimagesize($webimage);
$imagetype= $imageinfo['mime'];
if($imagetype=='image/jpeg'){
    if(stripos($pathend,'.jpg')==0){
        $newpathend = $pathend.'.jpg'; // if image end is't '.jpg', add '.jpg'
    }else if(stripos($pathend,'.jpeg')==0){
        $newpathend = $pathend.'.jpeg'; // if image end is't '.jpg', add '.jpeg'
    }else{
        $newpathend = $pathend;// if image end is '.jpg' or '.jpeg', do not change
    }
}
if($imagetype=='image/png'){
    if(stripos($pathend,'.png')==0){
        $newpathend = $pathend.'.png'; // if image end is't '.png', add '.png'
    }else{
        $newpathend = $pathend;// if image end is '.png', do not change
    }
}
if($imagetype=='image/gif'){
    if(stripos($pathend,'.gif')==0){
        $newpathend = $pathend.'.gif'; // if image end is't '.gif', add '.gif'
    }else{
        $newpathend = $pathend;// if image end is '.gif', do not change
    }
}

6 个答案:

答案 0 :(得分:5)

为什么不使用preg_match?

if( preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $webimage, $matches) ) {
    // matching file extensions are in $matches[1]
}

答案 1 :(得分:4)

您可以尝试这样

$type=Array(1 => 'jpg', 2 => 'jpeg', 3 => 'png', 4 => 'gif'); //store all the image extension types in array

$imgname = ""; //get image name here
$ext = explode(".",$imgname); //explode and find value after dot

if(!(in_array($ext[1],$type))) //check image extension not in the array $type
{
    //your code here
}

答案 2 :(得分:1)

此功能pathinfo可能会对您有所帮助。

答案 3 :(得分:1)

这适用于jpg以及jpeg和大写字母。 它也适用于testing.the.bicycle.jpg

等文件名

试试https://regex101.com/r/gI8uS1/1

public function is_file_image($filename)
{
   $regex = '/\.(jpe?g|bmp|png|JPE?G|BMP|PNG)(?:[\?\#].*)?$/';

   return preg_match($regex, $filename);
}

答案 4 :(得分:0)

使用 strops

if (strpos($your_text,'.png') !== false) {
        //do something
 } else if (strpos($your_text,'.jpg') !== false) {
        //do something
 } else if (strpos($your_text,'.gif') !== false) {
        //do something
 }

希望它会有所帮助!)

答案 5 :(得分:-1)

$Extension=strrev(substr(strrev($fileName),0,strpos(strrev($fileName),'.')));
if(preg_match('/png|jpg|jpeg|gif/',$Extension))
{ 
    true 
}
else
{ 
    false
}
相关问题