0

我有这个 PHP 代码可以将文件从一个目录复制到另一个目录,而且效果很好,但是,如何只复制以字母“AUW”(减引号)结尾的文件?请记住,该文件是无扩展名的,因此它实际上以字母 AUW 结尾。

同样在复制后,我不希望从源文件夹中删除文件。

// Get array of all source files
$files = scandir("sourcefolder");
// Identify directories
$source = "sourcefolder/";
$destination = "destinationfolder/";
// Cycle through all source files
foreach ($files as $file) {
  if (in_array($file, array(".",".."))) continue;
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file)) {
    $delete[] = $source.$file;
  }
}
// Delete all successfully-copied files
foreach ($delete as $file) {
  unlink($file);
}
4

5 回答 5

2

您可以使用函数glob

foreach (glob("*AUW") as $filename) {
   // do the work...
}
于 2012-07-26T14:35:27.717 回答
2
foreach ($files as $file) {
  if (in_array($file, array(".",".."))) continue;
  if (!endsWith($file, "AUW")) continue;
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file)) {
    // comment the following line will not add the files to the delete array and they will
    // not be deleted
    // $delete[] = $source.$file;
  }
}

// comment the followig line of code since we dont want to delete
// anything
// foreach ($delete as $file) {
//   unlink($file);
// }

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) return true;

    return (substr($haystack, -$length) === $needle);
}
于 2012-07-26T14:38:11.527 回答
1

使用substr() 方法获取文件名的最后三个字母。这将返回一个可用于逻辑比较的字符串。

if( substr( $file, -3 ) == 'AUW' )
{
  // Process files according to your exception.
}
else
{
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file)) {
    $delete[] = $source.$file;
}
于 2012-07-26T14:39:21.583 回答
1

您想使用该glob功能。

foreach( glob( "*.AUW" ) as $filename )
{
      echo $filename;
}

http://php.net/manual/en/function.glob.php

于 2012-07-26T14:35:47.713 回答
0

谷歌搜索太难了吗?我会给你一个提示 - 用于substr()查看最后 3 个字母是否为“AUW”

于 2012-07-26T14:34:52.030 回答