user1012032
user1012032

Reputation:

Translating string to another lang using array

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.";

Upvotes: 3

Views: 61

Answers (3)

hakre
hakre

Reputation: 197795

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.

Upvotes: 1

chapkom
chapkom

Reputation: 54

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

Upvotes: 0

antyrat
antyrat

Reputation: 27765

You can do that with str_replace function:

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

Upvotes: 0

Related Questions