如何使用PHP字符串endsWith从读取中跳过文件?
我想简单地跳过文件名以“@2x”结尾的文件,并在以下代码中实现:如何使用PHP字符串endsWith从读取中跳过文件?,php,arrays,string,filenames,glob,Php,Arrays,String,Filenames,Glob,我想简单地跳过文件名以“@2x”结尾的文件,并在以下代码中实现: $fullres = glob("gallery/*.*"); for ($i=0; $i<count($fullres); $i++) { $num = $fullres[$i]; echo '<a href="
$fullres = glob("gallery/*.*");
for ($i=0; $i<count($fullres); $i++)
{
$num = $fullres[$i];
echo '<a href="'.$num.'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i=/'.$num.'" alt="" /></a>';
}
$fullres=glob(“gallery/*.*);
对于($i=0;$i是的,您可以使用substr()
在定义$num后添加此行
您还可以简化代码
<?php
$fullres = glob("gallery/*.*");
foreach($fullres as $num)
{
if(substr($num, -3) == '@2x') continue;
echo '<a href="'.$num.'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i=/'.$num.'" alt="" /></a>';
}
?>
使用DirectoryIterator的解决方案
<?php
foreach (new DirectoryIterator('gallery/') as $fileInfo) {
if($fileInfo->isDot() || substr($fileInfo->getFileName(), -3) == '@2x')) continue;
echo '<a href="'.$fileInfo->getFilename().'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i=/'.$fileInfo->getFilename().'" alt="" /></a>';
}
?>
您不应该使用substr()
cuz,因为您假设文件名没有句点,而应该使用pathinfo
<?php
$fullres = glob("gallery/*.*");
foreach($fullres as $num) {
$fetch_file_name = pathinfo($num); //Fetch the file name with extension
$match_str = substr($fetch_file_name['filename'], -3); //Crop the file name
if($match_str != '@2x') {
echo '<a href="'.$num.'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i=/'.$num.'" alt="" /></a>';
}
}
?>
一个选项是使用过滤从glob()返回的数组
在此处输入代码
$fullres=glob(“画廊/*”);
对于($i=0;$i
试试看是的,但这是为什么要这样做?代码块不会显示您自己试图解决它的任何尝试。但这只会导致文件的链接不显示。并且不会阻止文件读取。那么为什么不使用DirectoryIterator?您想实现什么?我建议使用FileSystemEmitter(或者GlobiIterator),而不是DirectoryIterator。这一个工作正常,但最后缺少“}”。@user2396523抱歉,我在编辑时错过了,谢谢你提醒我:)
<?php
$fullres = glob("gallery/*.*");
foreach($fullres as $num) {
$fetch_file_name = pathinfo($num); //Fetch the file name with extension
$match_str = substr($fetch_file_name['filename'], -3); //Crop the file name
if($match_str != '@2x') {
echo '<a href="'.$num.'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i=/'.$num.'" alt="" /></a>';
}
}
?>
$fullres = glob("gallery/*.*");
$files = preg_grep('/@2x$/', $fullres, PREG_GREP_INVERT);
foreach ($files as $num)
{
// ...
}
enter code here
$fullres = glob("gallery/*.*");
for ($i = 0; $i < count($fullres); $i++) {
$num = $fullres[$i];
$info = pathinfo($num);
$file_name = basename($num,'.'.$info['extension']);
if(substr($file_name, -3) != "@2x"){
echo '<a href="'.$num.'" ><img src="/slir/?w=60&h=80&c=3x4&q=85&i/'.$num.'" alt="" /></a>';
}
}