勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

UTF-16にエンコードされている文字列をUTF-8へデコード

   2024/03/04  PHP

エンコードされている文字列であまり見かけない感じのものがあった。UTF-8やShift-JIS、EUC-JPではなく、色々調べるとUTF-16でエンコードされていた。以下でUTF-8にデコードできた。

 

ソースコード

<?php
$body = '\u30c6\u30b9\u30c8';
$decoded = preg_replace_callback(
    '|\\\\u([0-9a-f]{4})|i', 
    function($matched){
        return mb_convert_encoding(pack('H*', $matched[1]), 'UTF-8', 'UTF-16');
    }, 
    $body
);
echo $decoded;//テストと表示される。

 

参考サイト

http://kanonji.info/blog/2014/07/09/php%E3%81%A7unicode%E3%82%A8%E3%82%B9%E3%82%B1%E3%83%BC%E3%83%97%E3%82%B7%E3%83%BC%E3%82%B1%E3%83%B3%E3%82%B9%E3%82%92%E3%83%87%E3%82%B3%E3%83%BC%E3%83%89%E3%81%99%E3%82%8B/

 - PHP

  関連記事

PHPで「operator not supported for strings」エラーの対応方法

PHPにて「Fatal error: [] operator not suppo ...

レンタルサーバでPHPのsystem関数やexec関数が使用できずにエラーが出力される

レンタルサーバ上でPHPのsystem関数を実行しようとすると「Fatal er ...

PHPのsetcookieで「Cannot modify」エラーの対応方法

PHPでsetcookieを使うと「Warning: Cannot modify ...

Opauthで「Please change the…」エラーの対応方法

Opauthを使用中に「Notice: Please change the va ...

PHPでGoogle翻訳を手軽に扱えるライブラリ「google-translate-php」の利用方法

サイト内で一部テキストのGoogle翻訳を行いたい。ただ、Google Clou ...