Как я могу добавить номер к имени файла в php - PullRequest
0 голосов
/ 19 апреля 2020

Goodevening всем, как я могу добавить число к имени файла в php. Позволь мне объяснить; Я хочу сохранить файл, используя dropzone, но я хочу переименовать файл, если он существует в папке. Я записал этот код, но регулярное выражение не работает, а также, если возможно, вставить число до расширения файла, как это делает google chrome.

if(file_exists($target_file)){
    if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
        $target_file= $target_path."(1)".$name;
    }else{
        $pos=preg_match_all($target_file, "'('[0-9]{1,}')'");
        $pos=$pos++;
        $pos1=strpos($pos, $target_file, ")");
        $pos1=$pos1-$pos;
        $num=substr($target_file, $pos, $pos1);
        $num = (int)$num;
        $num =$num++;
        $sostituisci="(".$num.")";
        $target_file=preg_replace("'('[0-9]{1,}')'", $sostituisci, $target_file);
    }
}

$ name - это имя файла, который я хочу сохранить с расширением, первый $ target_file кода содержит полный путь + имя файла

$ target_file - это строка типа /dropzone/upload/filename.txt и $ name это строка вроде filename.txt. Если $ targetfile существует, я бы переименовал $ name в имя файла (1) .txt или filename (2) .txt и т. Д.

, также принимаются другие решения, такие как js библиотека.

Ответы [ 2 ]

0 голосов
/ 20 апреля 2020

Я нашел решение idk, если оно наилучшее, потому что поиск и подстановка регулярных выражений часто выполняются, и кажется, что они потребляют ресурсы.

//this function insert the $number in the name of the file before .extension
function InsertBeforeExtension($filename,$number){
    $stmt = NULL;
    $format = explode('.', $filename);
    $i = 0;
    foreach($format as $key => $value){     
        if($value === end($format)){
            $stmt .= '('.$number.').'.$format[$i];
        }elseif($key === count($format)-2){
            $stmt .= $format[$i];
        }else{
            $stmt .= $format[$i].'.';
        }
    $i++;     
    }
return $stmt;
}

//this function check if there's a string like (number).ext in the name
//if yes increment the (number) in the string that become (number++).ext
//if no insert (1) before .ext
function insertnumber($string){
    $matches=array();
    $re = '/[(][0-9]+[)]\.[a-zA-Z]+/m';
    preg_match_all($re, $string, $matches, PREG_SET_ORDER, 0);
    if($matches[0][0]){
        //if (number).ext is present
        $re = '/[(][0-9]+[)]/m';
        $str = $matches[0][0];
        //select the (number) only
        preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
        //remove parethesis
        $str=substr($matches[0][0],1,-1);
        //cast sting to an int for add a number
        $int = (int)$str;
        $int++;
        //replace the last (number) match in the name of the file with (number++)
        $re = '/(.*)[(][0-9]+[)]/m';
        $subst = '${1}('.$int.')';
        $result = preg_replace($re, $subst, $string);
    }else{
        //if (number).ext is not present insert (1) before .ext
        $result=InsertBeforeExtension($string,1);
    }
    return $result;
};

$target_file = $target_path.$name;
//If the file exist repeat to find the number of file that doesn't exist
        if( file_exists( $target_file )) {
            while(file_exists( $target_file )){
                $name=insertnumber($name);
                $target_file = $target_path.$name;
            }
        }

Единственная проблема если вы загрузили файл с именем наподобие file (3) .txt и загрузили другой файл с тем же именем, эта функция переименовала его в file (4) .txt, а не в file (3) (1) .txt, но для моя область применения это не важно

Я прокомментировал код, пытаясь быть максимально понятным, это решение, кажется, работает хорошо, но я не вычисляю производительность.

0 голосов
/ 19 апреля 2020

Я предполагаю, что вы имеете в виду этот набор кода здесь.

if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
    $target_file= $target_path."(1)".$name;
}

insert the number before the extension of the file

РЕДАКТИРОВАТЬ: Используйте explode () и переформатируйте ext.

ПРИМЕР :

$target_path = "/assets/imgages/";
$name = 'img.jpg';
$name = explode('.', $name);
$format = $name[0].'(1).'.$name[1];
$path = $target_path.$format;

Создает следующую строку:

/assets/img/notes(1).txt

Принимать несколько точек в строке.

$filename = 'company.jobtitle.field.text';  

function formatDuplicateExtension($filename){
    $stmt = NULL;
    $format = explode('.', $filename);
    $i = 0;
    foreach($format as $key => $value){     
        if($value === end($format)){
            $stmt .= '(1).'.$format[$i];
        }elseif($key === count($format)-2){
            $stmt .= $format[$i];
        }else{
            $stmt .= $format[$i].'.';
        }
    $i++;     
    }
return $stmt;
}

echo formatDuplicateExtension($filename);

$filename = 'company.jobtitle.field.text';

ВЫХОДЫ: // -> /assets/imgages/company.jobtitle.field(1).text

$name = 'trees.vac2012.img.jpg';

ВЫХОДЫ: // -> /assets/imgages/trees.vac2012.img(1).jpg

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...