Problems with str_replace

Hello people!

I’m having problems using the str_replace command.

I want to use two files. One contains which words to replace, and the other contains which words to replace them with.

My script looks like this:

$file = file_get_contents(‘example.html’);
$originalwords = “originalwords.txt”;
$newwords = “newwords.txt”;

$result = str_replace($originalwords, $newwords, $file);

echo $result;

For some reason $file isn’t being affected by my str_replace command.

Any ideas where I’m going wrong?

Cheers.
Lee.

Well sure…you are not pulling in the contents of the two files according to the code you posted…unless you are trying to replace the file names contained within the source…

So how would I pull the contents into two arrays to use in the str_replace command?

I’ve tried:

$file1 = file_get_contents(‘originalwords.txt’);
$originalwords = explode("
",$file1);

$file2 = file_get_contents(‘newwords.txt’);
$newwords = explode("
",$file2);

but this didn’t seem to work.

Basically, I want to do a str_replace using two text files instead of arrays, but it isn’t working…

Try this:



//  orriginalwords.txt
tracy
diana
helen

// newords.txt
tom
dick
harry

// example.html
tracy
diana
helen

<?php

function fred($str)
{
  echo '<pre>'; print_r($str); echo '</pre>';
}



       $file1 = file_get_contents('originalwords.txt');
        $originalwords = explode("\
",$file1);

        $file2 = file_get_contents('newwords.txt');
        $newwords = explode("\
",$file2);

        $file = file_get_contents('example.html');
        echo 'before: <br />';
        fred($file);

        $result = str_replace($originalwords, $newwords, $file);
        echo 'after:  <br />';
        fred($result);
?>

// output
before:
tracy
diana
helen

after:
tom
dick
harry


I have tried this locally, copy the files, etc and once working then replace with your content and spot the differences.