~drscream
Search and Replace a Loaded File (with PHP)
A simple to use script for loading a file, search and replacing words, and displaying the file.
// File to open
$file = '/path/to/file.txt';
// Search and Replace Arrays
$search = array('soda', 'hamburger', 'ice', 'food');
$replace = array('beer', 'pizza', 'water', 'drink');
// Open the file
$lines = file($file);
// Read through the file
foreach($lines as $line_num => $line) {
$text = preg_replace($search, $replace, $line);
echo $text."\n";
}
Send your comment by mail.
Sat 01/09/07, 1:26 pm
Hm, perhaps better use fopen() and appropriate reading functions to improve performance, and save memory! Additionally, if you think about the compile-time for regex functions, i would recommend the str_replace() function. If you are using OOP/sorta things anyway and do not care about anything performance-like thingies, echo str_replace($s, $r, file_get_contents($file)); does the same as above with less code ;)
/
Wed 05/09/07, 12:11 pm
Having problems when searching and replacing texts in a .doc file.. Works in .txt but not in .doc.. Any comments or suggestions? :)
/