我有这个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);
}
答案 0 :(得分:2)
您可以使用glob函数。
foreach (glob("*AUW") as $filename) {
// do the work...
}
答案 1 :(得分: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);
}
答案 2 :(得分:1)
您想使用glob
功能。
foreach( glob( "*.AUW" ) as $filename )
{
echo $filename;
}
答案 3 :(得分:1)
使用substr() method获取文件名的最后三个字母。这将返回一个可用于逻辑比较的字符串。
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;
}
答案 4 :(得分:0)
Google搜索太难了?
我会给你一个提示 - 使用substr()
查看最后3个字母是否为“AUW”
AH