Home > Backend Development > PHP Tutorial > How to Convert Unicode Escape Sequences to UTF-8 Characters in PHP?

How to Convert Unicode Escape Sequences to UTF-8 Characters in PHP?

Patricia Arquette
Release: 2024-12-15 19:57:14
Original
775 people have browsed it

How to Convert Unicode Escape Sequences to UTF-8 Characters in PHP?

Unicode Escape Sequences to UTF-8 Characters in PHP

This question provides a solution for decoding Unicode escape sequences like "u00ed" to their corresponding UTF-8 encoded characters in PHP. The user mentions that finding similar questions hasn't yielded satisfactory results.

To address this, the answer offers two preg_replace_callback functions. The first function handles Unicode escape sequences based on UCS-2BE:

$str = preg_replace_callback('/\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
Copy after login

If the Unicode escape sequences are based on UTF-16BE, such as in C/C /Java/Json, the second function can be used:

$str = preg_replace_callback('/\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);
Copy after login

By utilizing these functions, the Unicode escape sequences can be successfully decoded to their corresponding UTF-8 encoded characters.

The above is the detailed content of How to Convert Unicode Escape Sequences to UTF-8 Characters in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template