I am trying to
- open and read a file,
- Search a few words within the file,
- Replace these words with some other words,
- Put content into the file again.
The words for search and replace are taken dynamically from user input boxes. Here's the code I am going with,
$filename = 'test1.txt';
($handle = fopen($filename, 'r+')) or die();
$content = fread($handle, filesize($filename));
echo $content.'<br>'.'<br>';
if (isset($_POST['findtext']) && isset($_POST['replacetext'])) {
$findtext = $_POST['findtext'];
$replacetext = $_POST['replacetext'];
if (!empty($findtext) && !empty('$replacetext')) {
$ftxtarray = explode( ',', strtolower($findtext));
$rtxtarray = explode(',', strtolower($replacetext));
// code?
echo $content;
} else {
echo 'Please type in "Replace:" words and "Replace with:" words..';
}
}
And the HTML,
<form action="firstfile.php" method="POST">
<br>Replace:<br>
<input type="text" name="findtext"><br>
Replace with:<br>
<input type="text" name="replacetext"><br>
<input type="submit" value="Submit">
Lets say "test1.txt" contains few words including "John Doe" and user types in "John,Doe" in the "Replace:" field and "Richard,Roe" in the "Replace with:" field. Which method should I use to replace the specified words?