Jord123 Jord123 - 1 month ago 7x
PHP Question

PHP UTF-16 characters and str_replace

I'd like to translate a date from Russian and then change its format. When I use

str_replace('Сентября', 'September', $date);
it doesn't work because as the date function later suggests by throwing an error containing

The string isn't in UTF-8, but in UTF-16. How can I convert the string into UTF-8 without using mb_convert_encoding which my host doesn't support? I tried
iconv('UTF-16', 'UTF-8', $date);
also with LE BE, but neither helped

The error output looks like this

Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (1 сентября 2016 00:00)

DateTime->__construct('1 \xD1\x81\xD0\xB5\xD0\xBD\xD1\x82\xD1\x8F\xD0\xB1\xD1...', Object(DateTimeZone)) #


Try building an associative array like this for each month. Then you can use the russian month name as the array key and it'll return the US equivalent. Hope this helps.

$translator = array("Сентября" => "September");

echo $translator["Сентября"];


To pull the month from the date as specified in the example you can do this:

$str = '1 cентября 2016 00:00';
$russian_month = explode(' ', strtolower($str))[1];

$translator = array("cентября" => "September");
echo $translator[$russian_month];

This assumes that the month will always be appearing in the same order (day month year hh:mm). I also recommend typing the indexes in lowercase.