PHP技术求助:如何根据完整$Property_number匹配并展示对应图片
问题描述
我正在开发一个包含大量图片上传功能的项目,图片文件名保存规则如下:
$target_file = $target_dir . $Property_number . basename($_FILES["sittingroom"]["name"]);
我需要展示包含相同$Property_number的图片,但使用fnmatch()搜索'62c8706c06bf2'时,返回的却是仅前两位匹配的图片(如62a456ggfrshg、62bu737778384等),我需要的是完整包含该搜索字符串的图片。
尝试使用glob()但未匹配到任何内容,可能用法有误。附上我的PHP代码,请求帮助解决:
<?php $detg = '62c8706c06bf2'; $imagesDirectory = "singlerooms/"; if(is_dir($imagesDirectory)) { $opendirectory = opendir($imagesDirectory); while (($image = readdir($opendirectory)) !== false) { if(($image == '.') || ($image == '..')) { continue; } $imgFileType = pathinfo($image,PATHINFO_EXTENSION); if(($imgFileType == 'jpg') || ($imgFileType == 'png')){ fnmatch($image, $detg, $imagesDirectory = 0);{ echo ("<img src='singlerooms/".$image."' width='150' > "); } } } closedir($opendirectory); }; ?>
问题分析与解决
1. fnmatch()用法错误
你的fnmatch()调用完全搞反了参数顺序,正确的参数顺序是:
fnmatch(pattern, string, flags)
你把$image(文件名)放在了规则位置,$detg(要匹配的字符串)放在了待匹配字符串位置,而且第三个参数错误赋值了$imagesDirectory = 0,完全不符合语法。
另外,要匹配文件名中包含指定$detg字符串,需要给规则加上通配符*,比如"*{$detg}*",表示字符串前后可以有任意内容。
修正后的fnmatch判断逻辑:
if(fnmatch("*{$detg}*", $image)) { echo ("<img src='singlerooms/".$image."' width='150' > "); }
2. 更高效的glob()用法
既然文件名规则是Property_number + 原文件名,直接用glob()匹配符合规则的文件更高效,不需要遍历整个目录:
<?php $detg = '62c8706c06bf2'; $imagesDirectory = "singlerooms/"; // 匹配以$detg开头,后缀为jpg或png的文件 $matchedImages = glob("{$imagesDirectory}{$detg}*.{jpg,png}", GLOB_BRACE); foreach($matchedImages as $image) { // 提取文件名用于src路径 $fileName = basename($image); echo ("<img src='singlerooms/{$fileName}' width='150' > "); } ?>
GLOB_BRACE参数允许用{jpg,png}同时匹配两种后缀的文件,直接就能拿到所有符合条件的图片,无需手动过滤文件类型。
3. 完整修正后的原代码版本
如果想保留原有遍历方式,修正后的代码如下:
<?php $detg = '62c8706c06bf2'; $imagesDirectory = "singlerooms/"; if(is_dir($imagesDirectory)) { $opendirectory = opendir($imagesDirectory); while (($image = readdir($opendirectory)) !== false) { if(($image == '.') || ($image == '..')) { continue; } $imgFileType = pathinfo($image,PATHINFO_EXTENSION); if(($imgFileType == 'jpg') || ($imgFileType == 'png')){ // 修正fnmatch参数顺序和规则 if(fnmatch("*{$detg}*", $image)) { echo ("<img src='singlerooms/".$image."' width='150' > "); } } } closedir($opendirectory); }; ?>
内容的提问来源于stack exchange,提问作者Ezeomeke Stephen Ozioma
相关产品推荐
相关产品推荐

