A simple to use script for loading a file, search and replacing words, and displaying the file.
The path to the file to open.
// File to open $file = '/path/to/file/example.txt';
Set up the arrays to hold the search and replace words. Seperate each word with a comma and place each one in ("")
// Search and Replace Arrays
$search = array ('beer','pizza','hamburger','ice','food');
$replace = array ('soda','calzone','hotdog','water','drink');
Set up a handler to open the file and open it.
// Read through the file $lines = file($file);
Begin reading the file and start searching through it line for line.
foreach ($lines as $line_num => $line)
{
Replace the words using the search/replace arrays.
$text = preg_replace($search, $replace, $line);
Print the results to the screen, you could also output these results to a new file. The choice is yours.
print $text; }
Here is the code in full, enjoy.
<?
// File to open
$file = '/path/to/file/example.txt';
// Search and Replace Arrays
$search = array('beer','pizza','hamburger','ice','food');
$replace = array('soda','calzone','hotdog','water','drink');
// Open the file
$lines = file($file);
// Read through the file
foreach($lines as $line_num => $line) {
$text = preg_replace($search, $replace, $line);
print $text;
}
?>
That is the end of the article, until next time... happy scripting.