Last active
October 3, 2018 09:28
-
-
Save AminulBD/be0dff113ed5a530f6caf752d7dce4ed to your computer and use it in GitHub Desktop.
Search and Replace all files in a directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SearchReplace | |
{ | |
private $src; | |
private $conf; | |
// You know what is this | |
public function __construct($conf) | |
{ | |
$this->src = dirname(__FILE__) . '/src/'; | |
$this->conf = $conf; | |
} | |
// Replace and save it on the dist | |
private function replace() | |
{ | |
$files = $this->getFiles(); | |
$chunked = array_chunk($files, 50, true); | |
$total = count($files); | |
$complated = 0; | |
foreach ($chunked as $items) { | |
foreach ($items as $item) { | |
$complated++; | |
$file = $this->src . $item; | |
$openFile = file_get_contents($file); | |
$replace = $openFile; | |
foreach ($this->conf as $conf ) { | |
if (isset($conf['search']) && isset($conf['replace'])) { | |
$replace = str_replace($conf['search'], $conf['replace'], $replace); | |
} elseif (isset($conf['pattern']) && $conf['content']) { | |
$replace = preg_replace($conf['pattern'], $conf['content'], $replace); | |
} | |
} | |
// Store file. | |
file_put_contents($file, $replace); | |
// Output Status | |
echo 'Changing: ' . $item.PHP_EOL; | |
echo $complated . ' of ' . $total.PHP_EOL; | |
} | |
} | |
} | |
// Get list of files | |
private function getFiles() | |
{ | |
$scan = scandir($this->src); | |
return array_diff($scan, array('..', '.')); | |
} | |
// Do the magic | |
public function magic() | |
{ | |
return $this->replace(); | |
} | |
} | |
$conf = [ | |
[ | |
'search' => '', | |
'replace' => '' | |
], | |
[ | |
'pattern' => '', | |
'content' => '', | |
], | |
]; | |
$data = new SearchReplace($conf); | |
$data->magic(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment