我需要验证字符串是否为图像文件名。
$aaa = 'abskwlfd.png';
if ($aaa is image file) {
echo 'it's image';
else {
echo 'not image';
}
我该怎么做?它将检测100个图像,所以它应该很快。我知道有一种文件类型验证方法,但我认为这很慢。。preg_match怎么样?它更快吗?我不擅长预赛。
提前谢谢。
试试这个:
<?php
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$src_file_name = 'abskwlfd.PNG';
$ext = strtolower(pathinfo($src_file_name, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}
?>
试试这个代码,
if (preg_match('/('.jpg|'.png|'.bmp)$/i', $aaa)) {
echo "image";
} else{
echo "not image";
}
也许你正在寻找这个:
function isImageFile($file) {
$info = pathinfo($file);
return in_array(strtolower($info['extension']),
array("jpg", "jpeg", "gif", "png", "bmp"));
}
- 我正在使用
pathinfo
来检索有关文件的详细信息,包括扩展名 - 我使用
strtolower
来确保扩展将与我们支持的图像列表匹配,即使是在不同的情况下 - 使用
in_array
检查文件扩展名是否在我们的图像扩展名列表中
尝试这个
$allowed = array(
'.jpg',
'.jpeg',
'.gif',
'.png',
'.flv'
);
if (!in_array(strtolower(strrchr($inage_name, '.')), $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
或strrchr它取字符串的最后一次出现。。或者其他一些概念。
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif',
'application/x-shockwave-flash'
);
if (!in_array($image_name, $allowed)) {
print_r('error message');
}else {
echo "correct image";
}
在这里,您可以使用STRTOLOWER函数,也可以在_array函数
试试这个:
$a=pathinfo("example.exe");
var_dump($a['extension']);//returns exe
是的,regex就是最好的选择。或者,您可以围绕"."
进行拆分,并对照图像扩展数组检查返回数组中的最后一个元素。我不是一个PHP的家伙,所以我不能为你写代码,但我可以写正则表达式:
^[a-zA-Z'.0-9_-]+'.([iI][mM][gG]|[pP][nN][gG]|etc....)$
这个相当简单。我知道你对regex没有太多经验,但这是一个:
^: start of string
[a-zA-Z'.0-9_-]: describes range of characters including all letters, numbers, and ._-
'.: "." character
([iI][mM][gG]|[pP][nN][gG]|etc....): | means or. So just put all image extensions you know here. Again, the brackets for case-insensitivity
如果你想匹配任何序列,那么不用括号里的东西和+,只需使用:
.*
"."匹配任何字符,"*"表示任何数量。所以这基本上只是说"没有限制"(除了换行符)
正如你在评论中看到的,我可能还错过了很多其他的东西。只要阅读这些内容,查看regex引用,您就可以了。
试试这个
使用pathinfo():
$ext = pathinfo($file_name, PATHINFO_EXTENSION); case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}