PHP:while循环 - 在条件中使用更改的变量

时间:2011-12-31 03:21:46

标签: php while-loop preg-replace

我在PHP中有一个while循环问题似乎可以使用&符号解决它,如果它在其他地方使它成为引用。以下是一个例子。我正在尝试将 _n 附加到文件名(在basename中)。如果有_1然后我希望它是_2,如果有_2我希望它是_3等等。出于某种原因,我无法在条件中更新$ filename变量,因此我认为它不会在循环中更改。

$dir = 'images';
$filename = '123.jpg';
$i = 0;
while (file_exists($dir.'/'.$filename)) {
    $filename = preg_replace('/^(\d*?)(\.jpg)$/',"$1_".(++$i)."$2",$filename);
}
echo $filename;

我做错了什么?

3 个答案:

答案 0 :(得分:3)

看起来您的正则表达式有点偏差,如果它已经存在,您就不会捕获_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

答案 1 :(得分:1)

如果您不想使用正则表达式并且您想确保在目录中获得所有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;
}

答案 2 :(得分:0)

这是一个使用函数而没有正则表达式的示例。这种方式适用于更广泛的环境。

即。任何文件扩展名都可以使用,并且,基本名称中允许使用下划线或句点

如果您不需要这些东西,那么使用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;
?>