用于拆分文件名的PHP代码,并将其重命名为文件中的内容

时间:2016-08-27 11:59:21

标签: php

我有很多文件,其中一些文件中包含“5010”,通常当我看到这些数字时,我打开文件并获取名称REF旁边的代码并粘贴它而不是5010,然后发送它到服务器,但我想通过一个PHP脚本,它可以自己完成这个任务,任何想法从哪里开始这个?

例如我的文件名是

"hasdbgf.5010.dfgur.fde"

我想删除“5010”,所以我打开文件:

DTM*405*2022~
N1*PR*AEA~
N3*151 AVENUE~
N4*06156~
REF*2U*60054~

我看到在REF * 2U为“60054”后,我将其重命名为:

"hasdbgf_60054_dfgur.fde"

1 个答案:

答案 0 :(得分:1)

我在5分钟内编写了这个脚本。只需将其放在您希望重命名操作的目录中即可。就这些。     

//expression to be found in file name
$find = '.5010.';

//directory name
//we will store renamed files here
$dirname = 'renamed_5010';
if(!is_dir($dirname))
    mkdir($dirname, 0777);

//read all files from a directory
//skip directories
$directory_with_files = 'C:\dir\path';
$dh  = opendir($directory_with_files);
$files = [];
while (false !== ($filename = readdir($dh)))
{
    if(in_array($filename, ['.', '..']) || is_dir($filename))
        continue;

    $files[] = $filename;
}

//iterate collected files
foreach($files as $file)
{
    //check if file name is matching $find
    if(stripos($file, $find) !== false)
    {

        //open file
        $handle = fopen($file, "r");
        if ($handle)
        {
            //read file, line by line
            while (($line = fgets($handle)) !== false)
            {

                //find REF line
                if(stripos($line, 'REF') !== false)
                {
                    //we are going to REF line reverse
                    $reverse = strrev($line);
                    $found = false;
                    $refnumber = [];

                    //find reference number
                    for($i = 0; $i < strlen($reverse); $i++)
                    {

                        if(is_numeric($reverse[$i]))
                        {
                            $found = true;
                            $refnumber[] = $reverse[$i];
                        }

                        if($found == true && !is_numeric($reverse[$i]))
                            break;
                    }

                    //glue refernce numbers
                    //check if reference number is not empty
                    $refnumber = strrev(join('', $refnumber));
                    if(!empty($refnumber))
                    {
                        $refnumber = '_' . $refnumber . '_';
                        $filerenamed = str_replace($find, $refnumber, $file);
                        copy($file, $dirname . '/' . $filerenamed);
                    }

                    echo $refnumber . "\n";
                }
            }

            //close file
            fclose($handle);
        }
    }
}