Artikel
Search and replace inside zip with PHP
Ever wanted to search and replace inside a zip container with PHP?
# this will replace every 'a' by 'A' inside every html file inside file.zip
replaceinzip("file.zip", '/a/', 'A', "/.+?html/");
exit();
function replaceinzip($zipfile, $search, $replace, $filefilter) {
# extract to random temp folder
$tempfolder=md5(mt_rand());
$zip = new ZipArchive;
if ($zip->open($zipfile) === TRUE) {
$zip->extractTo('./'.$tempfolder.'/');
$zip->close();
} else {
trigger_error(htmlentities("not a zip error"), E_USER_ERROR);
}
# replace in files
$files=rsearch($tempfolder, $filefilter);
foreach ($files as $file) {
$file_content = file_get_contents($file);
$file_content = preg_replace($search, $replace, $file_content);
file_put_contents($file,$file_content);
}
# create new temp zip
$zip = new ZipArchive();
if($zip->open($zipfile.'_temp', ZIPARCHIVE::OVERWRITE) !== true) {
return false;
}
# add files to new temp zip without foldername
$files=rsearch($tempfolder, "/.*/");
# add mimetype first to overcome epub checking errors
$zip->addFile($tempfolder.'/mimetype', "mimetype");
foreach($files as $file) {
$zip_filename = substr($file, strpos($file,'/') + 1);
if (file_exists($file) && is_file($file) && $zip_filename!="mimetype") $zip->addFile($file, $zip_filename);
}
$zip->close();
# rename new zip to old zip
rename($zipfile.'_temp', $zipfile);
# remove temp folder and files
delete($tempfolder);
return true;
}
# http://stackoverflow.com/questions/17160696/php-glob-scan-in-subfolders-for-a-file#17161106
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
#http://stackoverflow.com/questions/1334398/how-to-delete-a-folder-with-contents-using-php/1334425#1334425
function delete($path) {
if (is_dir($path) === true) {
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file) {
delete(realpath($path) . '/' . $file);
}
return rmdir($path);
} else if (is_file($path) === true) {
return unlink($path);
}
return false;
}
0 Kommentare