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

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?