【问题标题】:PHP UTF-16 characters and str_replacePHP UTF-16 字符和 str_replace
【发布时间】:2016-09-02 22:50:07
【问题描述】:

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

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

错误输出如下所示

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

【问题讨论】:

    标签: php encoding utf-8 str-replace multibyte


    【解决方案1】:

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

    $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');
    

    【讨论】:

    • str_replace 不适用于混合字符集。但是,还是有办法的。所以我要编辑我的答案并添加一个额外的方法。
    • 更准确地说,str_replace关心字符集 - 它适用于字节。如果字节匹配,str_replace 匹配。 (如果您忘记了字符并将 PHP 中的字符串视为一堆字节,那么很多事情就更有意义了。)
    猜你喜欢
    • 2016-10-25
    • 2016-05-31
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多