从目录中可用的所有文件(图像文件)的文件名中删除字符串,而不影响其扩展名
Remove string from filename for all files (image files) available in the directory without affecting its extensions
需要从文件名中删除用户请求的字符串。下面是我的功能。
$directory = $_SERVER['DOCUMENT_ROOT'].'/path/to/files/';
$strString = $objArray['frmName']; // Name to remove which comes from an array.
function doActionOnRemoveStringFromFileName($strString, $directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!strstr($file,$strString)) {
continue;
}
$newfilename = str_replace($strString,"",$file);
rename($directory . $file,$directory . $newfilename);
}
}
closedir($handle);
}
}
部分效果不错。但是这个例程中的错误是,重命名操作也会对文件的扩展名进行操作。我需要的是,只重命名文件并且不应该影响它的文件扩展名。请有任何建议。提前致谢:).
我自己编写的库具有其中一些功能。看:
//Returns the filename but ignores its extension
function getFileNameWithOutExtension($filename) {
$exploded = explode(".", $filename);
array_pop($exploded);
//Included a DOT as parameter in implode so, in case the
//filename contains DOT
return implode(".", $exploded);
}
//Returns the extension
function getFileExtension($file) {
$exploded = explode(".", $file);
$ext = end($exploded);
return $ext;
}
所以你用
$replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
$newfilename = $replacedname.".".getFileExtension($file);
检查它在这里工作:
http://codepad.org/CAKdCAA0
需要从文件名中删除用户请求的字符串。下面是我的功能。
$directory = $_SERVER['DOCUMENT_ROOT'].'/path/to/files/';
$strString = $objArray['frmName']; // Name to remove which comes from an array.
function doActionOnRemoveStringFromFileName($strString, $directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!strstr($file,$strString)) {
continue;
}
$newfilename = str_replace($strString,"",$file);
rename($directory . $file,$directory . $newfilename);
}
}
closedir($handle);
}
}
部分效果不错。但是这个例程中的错误是,重命名操作也会对文件的扩展名进行操作。我需要的是,只重命名文件并且不应该影响它的文件扩展名。请有任何建议。提前致谢:).
我自己编写的库具有其中一些功能。看:
//Returns the filename but ignores its extension
function getFileNameWithOutExtension($filename) {
$exploded = explode(".", $filename);
array_pop($exploded);
//Included a DOT as parameter in implode so, in case the
//filename contains DOT
return implode(".", $exploded);
}
//Returns the extension
function getFileExtension($file) {
$exploded = explode(".", $file);
$ext = end($exploded);
return $ext;
}
所以你用
$replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
$newfilename = $replacedname.".".getFileExtension($file);
检查它在这里工作: http://codepad.org/CAKdCAA0