RK26
RK26

Reputation: 383

str_replace string with a file.txt

I'm sorry I have asked about this before, but with different output. Here is my previous question that already answered. But its inefficient.

I want the searchword and replaceword are in one file. I think this method will be more easier. So i think my code should be like this:

$txt_search = file_get_contents("replaced.txt");
$txt_search = array_map( 'trim', explode("=", $txt_s) );
$txt_replace = file_get_contents("replaced.txt");
$txt_replace = array_map( 'trim', explode(";", $txt_r) );
$term = str_replace($txt_s, $txt_r, $last_tmp_);

And inside the replaced.txt file should be like this:

hello=hi; modern=fashionable; apple=banana;

So for the result i want 'hello' replaced by 'hi'. What should I change from my code? or is there another way?

Upvotes: 0

Views: 119

Answers (1)

Orangepill
Orangepill

Reputation: 24665

This should give you a map of replacements

$arr = parse_ini_string(str_replace(";", "\n", file_get_contents("replaced.txt")));

if you have control over the contents of the replaced.txt file just change the ;'s over to newlines and and use parse_ini_file("replaced.txt"); to get the same array, this might be a little saner to maintain.

then you can do the replacements with

$term = str_replace(array_keys($arr), array_values($arr), $last_tmp_);

Upvotes: 1

Related Questions