PHP UTF-16 characters and str_replace


PHP UTF-16 characters and str_replace

我想从俄语翻译一个日期,然后更改其格式。当我使用str_replace('Сентября', 'September', $date);时,它不起作用,因为日期函数稍后会抛出包含'xD1'x81'xD0'xB5'xD0'xBD'xD1'x82'xD1'x8F'xD0'xB1'xD1'x80'xD1'x8F

的错误。

字符串不是UTF-8格式,而是UTF-16格式。我如何将字符串转换为UTF-8而不使用我的主机不支持的mb_convert_encoding ?我也尝试了iconv('UTF-16', 'UTF-8', $date);与LE BE,但都没有帮助

错误输出如下所示

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)) #

尝试为每个月构建一个这样的关联数组。然后,您可以使用俄罗斯月份名作为数组键,它将返回与美国相同的名称。希望对你有帮助。

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

编辑:

要从示例中指定的日期中提取月份,您可以这样做:

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

这假设月份总是以相同的顺序出现(日月年hh:mm)。我还建议用小写字母输入索引。


将'September'转换为UTF-16,然后进行替换似乎有效。这是另一种方法。

function translateDate($from, $to, $str){
     $from = iconv('UTF-8','UTF-16BE', $from);
     $to = iconv ( 'UTF-8', 'UTF-16BE' ,  $to );
     $str = iconv ( 'UTF-8', 'UTF-16BE' , $str);
     $new = str_ireplace($from, $to,  $str);
     return iconv (  'UTF-16BE', 'UTF-8',  $new);
}
echo translateDate('сентября', 'September', '1 сентября 2016 00:00');