簡體   English   中英

將PHP字符串轉換為1個UTF-8字符

[英]Convert PHP String to 1 UTF-8 character

$caption = "Hello World \xF0"; // \xF0 is evaluated as one character
$input = $_POST["mes"]; // \xF0 is stored as four characters
// equivalent to:
$input = 'Hello World \xF0'; // \xF0 also stored as four characters

如何將$ input字符串編碼為\\ xF0也作為一個字符? 非常感謝你 !

<?php
$data = '\xF0\x9F\x98\x9A';

$pattern = '!
    \\\                     # a literal backslash
    x                       # followed by a literal x
    (                       # capture the following {
        [0-9a-fA-F]         #   any hexadecimal digit
        {2}                 #   actually two of them
    )                       # }
!x';

// replace all \xnn by "the byte nn"
$data = preg_replace_callback(
    $pattern,
    function($captures) {
        return chr( hexdec($captures[1]) );
    },
    $data
);

// $data contains now the byte sequence given by the hexadecimal notation
// but keep in mind that php3,4,5's core has no notion of character encoding
// a string is just a sequence of single bytes...

// I'm using a browser to display the result
// it must know that the output stream is utf-8 encoded
// default_charset will send the appropriate http response header for that
ini_set('default_charset', 'utf-8');

echo $data;

在我的Firefox中打印一個😚

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM