doushijia5684
doushijia5684
2015-01-22 05:59

从文件名中删除目录中可用的所有文件(图像文件)的字符串,而不影响其扩展名

已采纳

Need to remove user requested string from file name. This below is my function.

$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);
    }   
}

It works partially good. But the mistake what in this routine is, renaming action also takes on file's extensions. What i need is, Only to rename the file and it should not to be affect its file extensions. Any suggestions please. Thanks in advance :).

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drasebt1835 drasebt1835 6年前

    I have libraries written by myself that have some of those functions. Look:

    //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;
    }
    

    So you use

    $replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
    
    $newfilename = $replacedname.".".getFileExtension($file);
    

    Check it working here: http://codepad.org/CAKdCAA0

    点赞 评论 复制链接分享