比较字符串,在 PHP 中包含带有 == 的空格 [英] Comparing strings, containing space with == in PHP

查看:19
本文介绍了比较字符串,在 PHP 中包含带有 == 的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么这会在 PHP 中发生:

I am curious why this is happening in PHP:

'78' == ' 78' // true
'78' == '78 ' // false

我知道最好使用 strcmp 或至少使用 ===.我也知道当您将数字字符串与 == 进行比较时,如果可能,它们会被转换为数字.我也可以接受前导空格被忽略,所以 (int)' 78' 是 78,在第一种情况下答案是正确的,但我真的很困惑为什么它在第二种情况下是错误的.

I know that it's much better to use strcmp or the least ===. I also know that when you compare numerical strings with == they are casted to numbers if possible. I also can accept that the leading space is ignored, so (int)' 78' is 78, and the answer is true in the first case, but I'm really confused why it's false in the second.

我认为 '78' 被转换为 78'78' 被转换为 78,也是,所以它们是相同的,答案是正确的,但显然,情况并非如此.

I thought that '78' is casted to 78 and '78 ' is casted to 78, too, so they are the same and the answer is true, but obviously, that's not the case.

任何帮助将不胜感激!非常感谢您提前!:)

Any help will be appreciated! Thank you very much in advance! :)

推荐答案

这一切似乎又回到了 这个is_numeric_string_ex C 函数.

It all seems to go back to this is_numeric_string_ex C function.

=的实现开始=:

ZEND_API int ZEND_FASTCALL compare_function(zval *result, zval *op1, zval *op2) {
    ...
    switch (TYPE_PAIR(Z_TYPE_P(op1), Z_TYPE_P(op2))) {
        ...
        case TYPE_PAIR(IS_STRING, IS_STRING):
            ...
            ZVAL_LONG(result, zendi_smart_strcmp(op1, op2));

如果两个操作数都是字符串,它最终会调用 zendi_smart_strcmp...

If both operands are a string, it ends up calling zendi_smart_strcmp...

ZEND_API zend_long ZEND_FASTCALL zendi_smart_strcmp(zval *s1, zval *s2) {
    ...
    if ((ret1 = is_numeric_string_ex(Z_STRVAL_P(s1), Z_STRLEN_P(s1), &lval1, &dval1, 0, &oflow1)) &&
        (ret2 = is_numeric_string_ex(Z_STRVAL_P(s2), Z_STRLEN_P(s2), &lval2, &dval2, 0, &oflow2))) ...

调用 is_numeric_string_ex...

/* Skip any whitespace
 * This is much faster than the isspace() function */
while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r' || *str == '\v' || *str == '\f') {
    str++;
    length--;
}
ptr = str;

其中有显式代码可以在开头跳过空格,但不是在结尾处.

Which has explicit code to skip whitespace at the beginning, but not at the end.

这篇关于比较字符串,在 PHP 中包含带有 == 的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆