2011-12-31 85 views
1

我在PHP中遇到了一个while循环问题,似乎它可能已经使用&符号解决,如果它在其他地方可以使用它作为参考。下面是一个例子。我试图追加_n到文件名(在基本名称中)。如果有_1,那么我希望它是_2,如果有_2我希望它是_3等等。出于某种原因,我无法更新条件中的$ filename变量,所以我认为它在循环中没有发生变化。PHP:while循环 - 在条件下使用更改后的变量

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

我在做什么错?

回答

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 
+0

我刚刚得出同样的结论。 +1 – 2011-12-31 03:39:09

+0

正确。我怎么错过了。非常感谢。 – inhan 2011-12-31 03:41:01

+0

还有问题。我用/^(\d+)(_\d+)?(\.jpg)$/尝试了它,但没有运气。 – inhan 2011-12-31 03:55:16

1

如果你不想使用正则表达式,你要确保你有一个目录中的所有JPG文件,你可以使用​​3210和一些基本的字符串处理函数,像这样:

$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; 
} 
+0

谢谢。如果具有该名称的文件已经存在,则问题是将** _n **追加到基本名称。你最后一行是否将文件名从'123.jpg'改为'124.jpg',还是我误解了? – inhan 2011-12-31 04:04:12

+0

啊,我明白了 - 我误解了你的问题。我会做一些编辑。 – rdlowrey 2011-12-31 04:06:24

+0

它已经解决,但继续前进,如果你有一个替代解决方案,如果它不打扰你:) – inhan 2011-12-31 04:23:45

0

这里是一个使用函数但没有正则表达式的例子。这种方式适用于更广泛的情况。

即任何文件扩展名的作品,并且,下划线或周期中的基本部分

允许如果您不需要这些东西,然后使用的preg_replace()是清洁,看到迈克尔的回答。

<?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; 
?> 
+0

感谢您的替代方案。 – inhan 2012-01-04 00:57:51