[英]PHP: while loop - using the altered variable in the condition
I have a while loop issue in PHP that seems like it could have been solved using the ampersand sign to make it a reference if it were elsewhere. 我在PHP中有一个while循环问题似乎可以使用&符号来解决它,如果它在其他地方使它成为引用。 Below is an example. 以下是一个例子。 I'm trying to append _n to the filename (in the basename). 我正在尝试将_n附加到文件名(在basename中)。 If there's _1 then I want it to be _2, if there's _2 I want it to be _3 and so on. 如果有_1然后我希望它是_2,如果有_2我希望它是_3等等。 For some reason I can't update the $filename variable in the condition so I think it's not getting changed in the loop. 出于某种原因,我不能在条件中更新$ filename变量,所以我认为它不会在循环中被更改。
$dir = 'images';
$filename = '123.jpg';
$i = 0;
while (file_exists($dir.'/'.$filename)) {
$filename = preg_replace('/^(\d*?)(\.jpg)$/',"$1_".(++$i)."$2",$filename);
}
echo $filename;
What am I doing wrong? 我究竟做错了什么?
It looks like your regex is a little off, and you are not capturing the _n
if it already exists. 看起来你的正则表达式有点_n
如果已经存在,你就不会捕获_n
。
while (file_exists($dir.'/'.$filename)) {
$filename = preg_replace('/^(\d+)(.*)(\.jpg)$/',"$1_".(++$i)."$3",$filename);
//-------------------------------^^^^ Capture the _n if it exists
// And stick the number in with $1 and $3 (now the .jog)
}
echo $filename;
// Current files...
123_1.jpg
123_2.jpg
123.jpg
// Outputs 123_3.jpg
If you didn't want to use a regex and you wanted to make sure you got all the jpg files in a directory you could use glob()
and some basic string manipulation functions like so: 如果您不想使用正则表达式并且您想确保在目录中获得所有jpg文件,则可以使用glob()
和一些基本的字符串操作函数,如下所示:
$dir = 'images/';
foreach (glob($dir.'*.jpg') as $file) {
$ext = strpos($file, '.jpg'); // get index of the extension in string
$num = (int) substr($file, 0, $ext); // get the numeric part
$file = $num+1 . '.jpg'; // rebuild the file name
echo $file, PHP_EOL;
}
Here's an example using a function and no regex. 这是一个使用函数而没有正则表达式的示例。 This way works for a much wider range of circumstances. 这种方式适用于更广泛的环境。
ie any file extension works, and, underscores or period allowed in the basename 即任何文件扩展名的工作原理,以及basename中允许的下划线或句点
If you don't need those things then using preg_replace() is cleaner, see Michael's answer. 如果您不需要这些东西,那么使用preg_replace()更清晰,请参阅Michael的回答。
<?php
function nextUnusedFileName($path, $fileName){
$index = 1;
while (file_exists($path."/".$fileName))
{
$baseNameEndIndex = strrpos($fileName, '_');
$extensionStartIndex = strrpos($fileName, '.');
if($baseNameEndIndex <= 0){
$baseNameEndIndex = $extensionStartIndex;
}
$baseName = substr($fileName, 0, $baseNameEndIndex)."_".$index;
$extension = substr($fileName, $extensionStartIndex+1, strlen($fileName)-$extensionStartIndex);
$fileName = $baseName.".".$extension;
$index++ ;
}
return $fileName;
}//end nextUnusedFileName
//main
$dir = "images";
$filename = "123.jpg";
$filename = nextUnusedFileName($dir, $filename);
echo $filename;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.