【问题标题】:Remove string from filename for all files (image files) available in the directory without affecting its extensions从文件名中删除目录中所有可用文件(图像文件)的字符串,而不影响其扩展名
【发布时间】:2015-03-20 20:28:11
【问题描述】:

需要从文件名中删除用户请求的字符串。下面是我的功能。

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

它部分工作良好。但是这个例程中的错误是,重命名操作也会影响文件的扩展名。我需要的是,只重命名文件,它不应该影响它的文件扩展名。请有任何建议。在此先感谢:)。

【问题讨论】:

    标签: php image rename str-replace file-rename


    【解决方案1】:

    我有自己编写的库,其中有一些功能。看:

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

    【讨论】:

    • 兄弟,效果很好,但是这个程序有问题。意味着它仅在文件名除了扩展名之外不应有任何点时对文件执行操作。否则返回错误的结果。如果文件名包含多个点,如何摆脱它??
    • 抱歉延迟回复。此键盘链接已过期。无论如何我会接受这个作为答案。谢了,兄弟。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多