【问题标题】:How to print out the square root symbol when running a PHP script in a Windows 10 command prompt?在 Windows 10 命令提示符下运行 PHP 脚本时如何打印平方根符号?
【发布时间】:2017-03-13 14:26:12
【问题描述】:

对于在命令行中运行的 PHP (5.6) 脚本,我试图打印平方根符号,但没有这样做。相反,我得到了垃圾字符。

我已经阅读了许多关于将 unicode 字符从 PHP CLI 打印到命令行的问题/答案,但没有一个与我的示例完全相关。

我在 Windows 10 上使用我乐于使用的标准命令提示符 (cmd.exe)。

我正在使用 Consolas 字体并运行 chcp 65001 将提示设置为 utf-8。 *也尝试过 Lucida 控制台*。

// Square root symbol

echo "\u221A";
echo "\xe2\x88\x9a";
echo '√';

我试过iconv()json_decode()mb_convert_encoding()pack()都没有成功。

【问题讨论】:

  • @JayBlanchard 他已经在使用 chcp 65001,这是您所链接问题的答案。
  • 请使用 √
  • 这就是为什么我说'可能'@Dimi¯\_(ツ)_/¯
  • @Dimi 该答案还说要使用在这种情况下未使用的 Lucida 控制台字体,因此它可能仍然是相同的解决方案。

标签: php cmd command-line-interface unicode-string square-root


【解决方案1】:
<?
    echo "\u{221a}";
    echo json_decode('"\u221a"');
    echo html_entity_decode('&#x221a;', 0, 'UTF-8');
?>

使用“Consolas”字体的命令行测试会话:

W:\php-7.1.2-Win32-VC14-x64>type test.php
<?
    echo "\u{221a}";
    echo json_decode('"\u221a"');
    echo html_entity_decode('&#x221a;', 0, 'UTF-8');
?>
W:\php-7.1.2-Win32-VC14-x64>chcp
Página de códigos activa: 850

W:\php-7.1.2-Win32-VC14-x64>php test.php
√√√
W:\php-7.1.2-Win32-VC14-x64>chcp 65001
Página de códigos activa: 65001

W:\php-7.1.2-Win32-VC14-x64>php test.php
√√√
W:\php-7.1.2-Win32-VC14-x64>

编辑以适应 cmets - 在 PHP 5.6.30 上测试

<?
    $entity = '&radic;';

    // select the one you like the best
    $squareRoot = '√';
    $squareRoot = html_entity_decode($entity);
    $squareRoot = mb_convert_encoding($entity, 'UTF-8', 'HTML-ENTITIES');

    printf('test: %s', $squareRoot);

?>

【讨论】:

  • 感谢您,但请查看我编辑的问题以获得输出 - 我使用的是 PHP 5.6
  • 取得了更大的成功,但现在我有 ? 来应对和奇怪的地方,我需要 %s 两侧的空格,否则我只会得到 ??? 作为输出。
  • @u01jmg3,我无法得到你的结局?(用 5.6.19 测试)。我一直无法输出以控制台没有前缀的 unicode 字符。奇怪的是,如果您将输出重定向到文件,您将看到正确的输出。如果只需要控制台输出,可以使用printf(" \x08%s", $squareRoot);
  • 经过多次测试,一旦我了解了删除流氓字符所需的间距,我终于得到了一段工作代码。不过,感谢您让我与printf()html_entity_decode() 走上了正轨。请参阅我的答案以获取最终解决方案。认为迁移到 PHP 7 会使事情变得更简单。
【解决方案2】:


<?php
    shell_exec('chcp 65001'); // set to utf-8
    $formatter = "\033[0m%s\n"; // use white text
    $sqrt      = html_entity_decode('&radic;');
    $output    = sprintf($formatter, $sqrt);
    $output   .= sprintf($formatter, $sqrt);
    // Padding required on the last line to prevent miscellaneous chars printing to the console
    // (Double the total number of lines (3))
    $output   .= sprintf($formatter, $sqrt . str_repeat(' ', 3*2));
    echo rtrim($output, "\n");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多