Search code examples
phpzipphp-ziparchive

How to rename .txt files before being added to zip using ZipArchive()?


I am using ZipArchive() to zip a bunch of .txt files together. Can someone please give me an example how to remove the ID from the beginning of all .txt files before placing them in the zip?

For example:

  • 144-apples.txt
  • 2-oranges.txt
  • 25555-bananas.txt

will be:

  • apples.txt
  • oranges.txt
  • bananas.txt

in the zip.

$name = str_replace(TXT_FILE_DIRECTORY . $group . '/', '', $file);
$zip->addFile($file, $name);

Solution

  • Something like this should work:

    <?php
        //Your $files array creation logic here
        foreach ($files as $file) {
            $fileName = preg_replace("/^\d+\-/", "", str_replace(TXT_FILE_DIRECTORY . $group . '/', '', $file));
            $zip->addFile($file, $fileName);
        }
    ?>