Skip to content

Instantly share code, notes, and snippets.

@phcorp
Created March 16, 2018 15:48
Show Gist options
  • Save phcorp/3238c513bb376526d8732dea0b8d703d to your computer and use it in GitHub Desktop.
Save phcorp/3238c513bb376526d8732dea0b8d703d to your computer and use it in GitHub Desktop.
PHP replace in path
<?php
$root = './src';
$find = 'foo';
$replace = 'bar';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));
$count = 0;
foreach ($iterator as $file) {
if ($file->isDir() || 'php' !== $file->getExtension() || '.' === $file->getFilename()[0]) {
continue;
}
$path = $file->getRealPath();
file_put_contents(
$path,
preg_replace(
sprintf('/%s/', preg_quote($find, '/')),
$replace,
file_get_contents($path)
)
);
++$count;
}
echo "Replaced '$find' by '$replace' in $count files.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment