Skip to content

Instantly share code, notes, and snippets.

@AminulBD
Last active October 3, 2018 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AminulBD/be0dff113ed5a530f6caf752d7dce4ed to your computer and use it in GitHub Desktop.
Save AminulBD/be0dff113ed5a530f6caf752d7dce4ed to your computer and use it in GitHub Desktop.
Search and Replace all files in a directory.
<?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