0

I am trying to

  1. open and read a file,
  2. Search a few words within the file,
  3. Replace these words with some other words,
  4. 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?

4
  • 1
    What's in test.txt? Can you skip that part (just put the contents in a string) and give a clear expected input and output example? See: stackoverflow.com/help/mcve Commented Aug 6, 2018 at 0:17
  • @ggorlen "test1.txt" is the file (residing in the same directory ) I am opening to check the specific words, ( which are taken from a input box) and if they exist, then they should be replaced with some other words.(also taken from another input box) Commented Aug 6, 2018 at 0:31
  • I realize that, but what's the content in that file? What's the expected input and output? What's wrong with your current code (e.g., what part of the process are you stuck on)? Did you read the MCVE? Your code is not valid PHP as it is written. Commented Aug 6, 2018 at 0:34
  • @ggorlen I edited the question so it will be much clearer. I am not sure of the function which I'll have to use here. Commented Aug 6, 2018 at 1:25

1 Answer 1

1

Use str_replace() and put in first parameter array of words to find, in second parameter array with the exact length as the first one, in third contents of a file loaded into variable, and you're good to go.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.