3

I want to translate all the keys from the array that occur in this string:

$bar = "It gonna be tornado tomorrow and snow today.";

and replacing it with the value using this array:

 $arr = array(
   "tornado" => "kasırga",
   "snow" => "kar"
);

So the output will be:

$bar = "It gonna be kasırga tomorrow and kar today.";

3 Answers 3

1

The function you're looking for is called string-translate, written in it's short form as strtrDocs:

$bar = strtr($bar, $arr);

Contrary to the popular belief in the other answers, str_replace is not safe to use as it re-replaces strings which is not what you want.

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

1 Comment

Thank you for this great explanation. This is now stuck on my head :) Thanks to others too.
0

You can do that with str_replace function:

$tmp = str_replace(array_keys($arr), array_values($arr), $bar);

Comments

0
foreach($arr as $key=>$value) {
    $bar = str_ireplace($key, $value, $bar);
}

Comments

Your Answer

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