RK26
RK26

Reputation: 383

str_replace string in a file.txt with another file.txt

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.

Upvotes: 1

Views: 142

Answers (1)

Andrey Volk
Andrey Volk

Reputation: 3549

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_);

Upvotes: 2

Related Questions