我有这个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);
}
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);
}
您可以使用函数glob。
foreach (glob("*AUW") as $filename) {
// do the work...
}
您想要使用glob
函数。
foreach( glob( "*.AUW" ) as $filename )
{
echo $filename;
}
http://php.net/manual/en/function.glob.php
使用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;
}
谷歌搜索太难了吗?我会给你一个提示-用substr()
看看最后3个字母是否是"AUW"
AH