Replace text
If you need to replace a word, use the str_replace() function.
$from = 'США';
$to = 'USA';
str_replace($from, $to, 'Translate: США'); // Translate: USA
You can also be implemented as an array:
$tranlates = [
'США' => 'USA',
'Нью-Йорк' => 'New York',
'Вашингтон' => 'Washington'
];
str_replace(array_keys($tranlates), array_values($tranlates), 'Translate: США'); // Translate: USA
In this case, each element of the array is checked, i.e. when the function sees and replaces the word “USA”, it still goes on to check the next elements of the array.
$tranlates = [
'США и Нью-Йорк' => 'USA и Нью-Йорк',
'Нью-Йорк' => 'New York',
'Вашингтон' => 'Washington'
];
str_replace(array_keys($tranlates), array_values($tranlates), 'Translate: США и Нью-Йорк'); // Translate: USA и New York
In the example above, it is clear that the replacement is with the word "США и Нью-Йорк", but in the end, "USA и New York" is displayed, since in one of the following elements "Нью-Йорк" is replaced with "New York".
If you want to output exactly what is specified in the value (in the example above, the expected output is "USA и Нью-Йорк"), then you can use the strtr() function.
$tranlates = [
'США и Нью-Йорк' => 'USA и Нью-Йорк',
'Нью-Йорк' => 'New York',
'Вашингтон' => 'Washington'
];
strtr('Translate: США и Нью-Йорк', $tranlates); // Translate: USA и Нью-Йорк
Поддержать автора
Все статьи создаются и поддерживаются одним человеком,
если вам нравится контент, вы можете поддержать автора сайта
