php - 如何将 unicode 转换为 utf-8 字符串

php - how to convert unicode to utf-8 string

我有这样的字符串:

%d8%b7%d8%b1%d8%a7%d8%ad%db%8c-%d8%a7%d9%be%d9%84%db%8c%da%a9%db%8c%d8%b4%d9%86-%d9%81%d8%b1%d9%88%d8%b4%da%af%d8%a7%d9%87%db%8c

页面的meta标签设置为utf-8

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

我想将此 unicode 转换为纯可读的 utf-8 字符串

我测试了很多代码,这是我最后的代码:

 function convertFarsi($str) {
        return html_entity_decode(preg_replace('/\\u([a-f0-9]{4})/i', '&#x;', $str),ENT_QUOTES, 'UTF-8');
    }

而且它不起作用。 如何将这些 un​​icode 转换为 utf8 字符串?

这似乎可以做到:

<?php
$s = '%d8%b7%d8%b1%d8%a7%d8%ad%db%8c-%d8%a7%d9%be%d9%84%db%8c%da%a9%db%8c%d8%b4%d9%86-%d9%81%d8%b1%d9%88%d8%b4%da%af%d8%a7%d9%87%db%8c';
$t = urldecode($s);
var_dump($t == 'طراحی-اپلیکیشن-فروشگاهی');

https://php.net/function.urldecode

您可以使用url_decode得到以下结果:

    <?php
    
    $string = '%d8%b7%d8%b1%d8%a7%d8%ad%db%8c-%d8%a7%d9%be%d9%84%db%8c%da%a9%db%8c%d8%b4%d9%86-%d9%81%d8%b1%d9%88%d8%b4%da%af%d8%a7%d9%87%db%8c';
    
    $outpout = urldecode($string);
    
    echo $outpout; // طراحی-اپلیکیشن-فروشگاهی

此函数不解码 unicode 字符。我写了一个函数。

function unicode_urldecode($url)
{
    preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);
   
    foreach ($a[1] as $uniord)
    {
        $dec = hexdec($uniord);
        $utf = '';
       
        if ($dec < 128)
        {
            $utf = chr($dec);
        }
        else if ($dec < 2048)
        {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
        else
        {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
       
        $url = str_replace('%u'.$uniord, $utf, $url);
    }
   
    return urldecode($url);
}

Source Demo