Ad

Str_replace String In A File.txt With Another File.txt

- 1 answer

I want to replace some string in searchword.txt file with replaceword.txt file, but with my php code it can only replace the first two strings, i want to replace all the strings in the file.

here is my php code:

$txt_s = file_get_contents("searchword.txt");
$txt_s = explode(";", $txt_s);
$txt_r = file_get_contents("replaceword.txt");
$txt_r = explode(";", $txt_r);
$term = str_replace($txt_s, $txt_r, $last_tmp_);

here is how my searchword.txt file looks like:

hello; modern; corn; banana; apple;

here is how my replaceword.txt file looks like:

goodbye; fashionable; popcorn; monkey; sweet;

how can i replace all the strings, not just first two strings? or may be any different way to do this please let me know.

Ad

Answer

You have to strip whitespaces for example with array_map()

$newarray = array_map('trim', $array);

Use:

$txt_s = file_get_contents("searchword.txt");
$txt_s = array_map( 'trim', explode(";", $txt_s) );
$txt_r = file_get_contents("replaceword.txt");
$txt_r = array_map( 'trim', explode(";", $txt_r) );
$term = str_replace($txt_s, $txt_r, $last_tmp_);
Ad
source: stackoverflow.com
Ad