【问题标题】:php - how to convert unicode to utf-8 stringphp - 如何将 unicode 转换为 utf-8 字符串
【发布时间】:2021-07-06 04:21:09
【问题描述】:

我有一个这样的字符串:

%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$1;', $str),ENT_QUOTES, 'UTF-8');
    }

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

【问题讨论】:

  • 您希望最终结果是什么?

标签: php string unicode utf-8 meta-tags


【解决方案1】:

你可以使用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; // طراحی-اپلیکیشن-فروشگاهی

【讨论】:

    【解决方案2】:

    此函数不解码 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

    【讨论】:

      【解决方案3】:

      这似乎可以做到:

      <?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

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 2010-09-21
        • 1970-01-01
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-02
        相关资源
        最近更新 更多