Translating a string to another language using an array

I want to translate all keys from an array that occur on this line:

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

      

and replacing it with a 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


source to share


3 answers


The function you are looking for is called string-translate, written in short form like strtr

Docs
:

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

      



Contrary to popular belief in other answers, it is str_replace

not safe to use as it re-replaces strings you don't want.

+1


source


You can do it with the function str_replace

:



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

      

0


source


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

      

0


source







All Articles