<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml xml:lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/vnd.wap.wml; charset=utf-8"/>
<meta http-equiv="Cache-Control" content="no-cache"/></head>
<card title="转换字符串至 NCR - Gracecode.com">
<p>看见 PHPChina 上转帖 <a href="http://www.coolcode.cn" title="http://www.coolcode.cn">andot</a> 的一篇文章《<a href="http://www.phpchina.com/viewnews_1107.html" title="http://www.phpchina.com/viewnews_1107.html">在任意字符集下正常显示网页的方法</a>》，非常的受用，于是将代码粘贴到这里收藏一下。</p>

<p>同个页面呈现不同语言字符的编码使用 UTF-8 是目前主流的应用方案。但是在一些极端的情况下，我们不得不在某些西方字符编码的页面上显示中文。</p>

<p>这时候，作者非常“取巧”地想到了使用 <a href="http://en.wikipedia.org/wiki/Numeric_character_reference" title="http://en.wikipedia.org/wiki/Numeric_character_reference">Numeric character reference</a> 解决这一问题。原理引述原文：</p>

<pre>原理很简单，就是把除了 ISO-8859-1 编码中前 128 个字符以外的所
有其他的编码都用 NCR(Numeric character reference) 来表示。比如
“汉字”这两个字，如果我们写成“&amp;#27721;&amp;#23383;”这种形式，
那么它在任意字符集下都可以正确显示。</pre><p>下面是我做的一些无关痛痒的修改，希望作者见谅：</p>

<pre>/**
 * nochaoscode - 转换字符串至 NCR
 *
 * @param  string $str     原字符串
 * @param  string $encode  原字符串的编码，默认 UTF-8
 * @return string 原字符串的 NCR 字符
 * @see http://en.wikipedia.org/wiki/Numeric_character_reference
 */
function nochaoscode($str, $encode = &quot;utf-8&quot;)
{
    if (!function_exists(&quot;iconv&quot;) || !function_exists(&quot;mb_strlen&quot;)) {
        return $str;
    }

    $str = iconv($encode, &quot;utf-16&quot;, $str); 
    for ($i = 0; $i &lt; mb_strlen($str); $i+=2) { 
        $code = ord($str{$i}) * 256 + ord($str{$i + 1}); 
        if ($code &lt; 128) {
            $output .= chr($code); 
        } else if ($code != 65279) {
            $output .= &quot;&amp;#&quot; . $code . &quot;;&quot;; 
        }
    }

    return $output; 
}</pre><p>原作者的 DEMO <a href="http://test.coolcode.cn/nochaoscode/" title="http://test.coolcode.cn/nochaoscode/">在这里</a>，但是不知道什么原因我打不开，请各位了解的告之。</p>


<p>
<a href="http://www.gracecode.com/wap/">Gracecode.com</a> |
<a href="http://www.gracecode.com/wap/d/595 ">Permalink</a>(<a href="http://www.gracecode.com/Archive/Display/595 ">xHTML</a>) |
<a href="http://www.gracecode.com/Trackback/Recieve/595/wvzzzw">Trackback</a> |
<a href="http://rss.gracecode.com">Rss</a>
</p>
</card>
</wml>