首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查图像文件名结尾是否不是.jpg、.jpeg、.png或.gif。

检查图像文件名结尾是否不是.jpg、.jpeg、.png或.gif。
EN

Stack Overflow用户
提问于 2012-04-07 16:01:50
回答 7查看 17.4K关注 0票数 3

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

代码语言:javascript
复制
$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
    }
}
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2012-04-07 19:31:07

你可以这样试一下

代码语言:javascript
复制
$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
}
票数 5
EN

Stack Overflow用户

发布于 2012-04-08 15:04:30

为什么不使用preg_match?

代码语言:javascript
复制
if( preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $webimage, $matches) ) {
    // matching file extensions are in $matches[1]
}
票数 6
EN

Stack Overflow用户

发布于 2012-04-07 16:07:51

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10052845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档