【问题标题】:PHP - why equal string are not equal with NumberFormatterPHP - 为什么相等的字符串不等于 NumberFormatter
【发布时间】:2021-12-13 04:59:08
【问题描述】:

为什么即使两个字符串相等,下面的代码回显也不相等?

$number = 1234567.89;
$expected = 'GBP 1,234,567.89';

$fmt = new NumberFormatter('en_AU@currency=GBP', NumberFormatter::CURRENCY);
$currency = $fmt->formatCurrency($number, 'GBP');

echo "$expected = $currency ?" . PHP_EOL;
echo $expected == $currency ? 'equals' : "not equal";

输出

GBP 1,234,567.89 = GBP 1,234,567.89 ?
not equal

任何帮助都会非常有帮助,谢谢

【问题讨论】:

    标签: php string equality numberformatter


    【解决方案1】:

    因为$expected 变量在“GBP”之后有一个空格

    $expected = 'GBP 1,234,567.89';
    

    不等于'GBP1,234,567.89';

    其实你可以调试它们;

    echo $expected;
    echo "<br>";
    echo $currency;
    

    【讨论】:

    • 嘿,我刚刚发现看到我添加的答案,这是因为一个特殊字符。谢谢
    【解决方案2】:

    好吧,尝试一些事情我得到了答案。 $exoected 和 $currency 有不同的编码。

    print_r([mb_detect_encoding($expected), mb_detect_encoding($currency)]);
    
    Array
    (
        [0] => ASCII
        [1] => UTF-8
    )
    

    $currency 中的空格字符是 194 ASCII 数字,而 $expected 中的空格字符是 32

    if (preg_match('/[^a-zA-Z0-9 ]+/', $number, $matches)) {
        print_r(ord($matches[0]));
        print_r(ord(' '));
    }
    

    希望这可以帮助那些摸不着头脑的人

    【讨论】:

    • 实际上可能是194 160(在使用 UTF-8 时,不能只查看单字节值),这将是一个不间断的空格。格式化程序会在这个位置使用一个是有道理的,因为您通常不希望在一行文本的末尾显示GBP,而是让1,234,567.89 进入下一个。
    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 2019-05-20
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多