【问题标题】:Displaying unicode symbol by outputting unicode with PHP function通过使用 PHP 函数输出 unicode 来显示 unicode 符号
【发布时间】:2012-08-27 14:05:48
【问题描述】:

我正在尝试将字符的 unicode 输出为我的 PHP 函数的返回类型,但是当我在实践中调用该函数时,它只输出没有“0x”而不是符号的代码。但是,如果我在我的 HTML 中明确声明 unicode,它会很好地输出符号。下面是我的代码的简化版本。为什么会这样?

在显示表格的 PHP 文件中:

<td><?php echo verifyMatch($a,$b) ?></td>

在我的另一个文件中的函数中:

function verifyMatch($_a,$_b){
  $_output = null;
  if (checkCondition()){
    $_output = 0x2714;
    // unicode for tick
  } else {
    $_output = 0x2718;
    // unicode for cross
  }
  return $_output;
}

【问题讨论】:

    标签: php html unicode


    【解决方案1】:

    就 PHP 而言,您的值 0x27140x2718 只是十六进制数字,它们分别存储为 27142718。实际上,PHP 应该将它们转换为十进制值。当输出到 HTML 中时,它们被输出为数字。

    如果您想以 HTML 格式输出它们并显示实际符号,请尝试在它们前面加上 &amp;#x,并在它们后面加上 ;

    <td><?php echo '&#x' . verifyMatch($a, $b) . ';'; ?></td>
    

    如果将它们转换为十进制值,您可以在它们前面加上&amp;# 而不是&amp;#x。添加的x 用于十六进制值。

    【讨论】:

      【解决方案2】:

      参考:php chr with unicode values

      function replace_unicode_escape_sequence($match) {
          return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
      }
      function unicode_chr ($chr) {
          $str = "\u".end(explode("+", $chr));
          return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
      }
      
      function verifyMatch($_a,$_b){
          $_output = null;
          if (checkCondition()){
             $_output = unicode_chr("U+2714");   // unicode for tick
          }
          else {
              $_output = unicode_chr("U+2718");   // unicode for cross
          }
          return $_output;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-22
        • 2020-06-30
        • 2010-12-14
        • 2013-05-29
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2011-03-01
        相关资源
        最近更新 更多