doushijia5684 2015-01-22 05:59
浏览 17
已采纳

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

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 2015-01-22 14:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献