-1

i found this code:

<?php
$path_to_file = 'c:\wamp\www\FindReplace\File.txt';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Paul",",HHH",$file_contents);
file_put_contents($path_to_file,$file_contents);
?>

It's working very well if it's only one file but how to do if i want to Find and Replace in all *.txt file of my folder?

THank you

Pacific
  • 195
  • 2
  • 6
  • 17
  • 2
    Can you use [sed](http://en.wikipedia.org/wiki/Sed) or it's required to be done with php? –  Oct 18 '11 at 11:53
  • `foreach(glob('/path/to/*.txt') as $filePath) { your code above }` – Gordon Oct 18 '11 at 11:55
  • possible duplicate of [Get the files inside a directory](http://stackoverflow.com/questions/1086105/get-the-files-inside-a-directory) – Gordon Oct 18 '11 at 11:57
  • possible duplicate of [How to add wildcard names to directory search in php](http://stackoverflow.com/questions/7774127/how-to-add-wildcard-names-to-directory-search-in-php) – genesis Oct 18 '11 at 11:58
  • if you are on windows you can just open a command prompt, cd to that folder and do `REN * *.jpg` – Gordon Oct 18 '11 at 12:23

3 Answers3

3

What about this? It should take care of running your replace on all .txt-files, regardless of how many sub-folders you got in your path folder.

$path = realpath(__DIR__ . '/textfiles/'); // Path to your textfiles 
$fileList = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);

foreach ($fileList as $item) {
    if ($item->isFile() && stripos($item->getPathName(), 'txt') !== false) {
        $file_contents = file_get_contents($item->getPathName());
        $file_contents = str_replace("Paul",",HHH",$file_contents);
        file_put_contents($item->getPathName(),$file_contents);
    }
}
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • i Have an error on line2 ( ! ) Parse error: syntax error, unexpected ':' – Pacific Oct 18 '11 at 12:19
  • Well, you would want to wrap your path with quotes, ie. ` – Industrial Oct 18 '11 at 14:55
  • Cool, thanks, this has really helped me a lot to change and saved too much of work and time, Great stuff! Though I have one more doubt, I have 3 to 4 lines to be replace one shot, is there any way to do it? – sammry Apr 26 '15 at 00:11
1
find /path/to/your/project -name '*.txt' -exec php yourScript.php {} \;

Then modify your script to use command line argument $argv[1] as the file path.

FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
0

You can use useful glob(), internal PHP function

$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');

So for your specific case:

<?php
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file);
    $file_contents = str_replace("Paul",",HHH",$file_contents);
    file_put_contents($path_to_file,$file_contents);
}
?>
genesis
  • 50,477
  • 20
  • 96
  • 125