在PHP源代码中,增量字符串的代码是什么?

goa*_*oat 5 php operators

PHP有一个功能,你可以在字符串上使用增量运算符.它的行为类似于里程表,一旦你到达一个范围的末尾,它就会"滚动".

<?php
$str = 'zy';
$str++;
echo "$str\n"; // zz
$str++;
echo "$str\n"; // aaa
Run Code Online (Sandbox Code Playgroud)

只是好奇PHP源代码在哪里.我经常在函数/扩展中查看源代码,但是这样的东西我不知道在哪里看.

使用基于Web的SVN链接到该文件将非常棒.

Bol*_*ock 10

该运算符的实现方便地位于zend_operators.c一个更方便的函数中increment_string():

static void increment_string(zval *str) /* {{{ */
{
    int carry=0;
    int pos=Z_STRLEN_P(str)-1;
    char *s=Z_STRVAL_P(str);
    char *t;
    int last=0; /* Shut up the compiler warning */
    int ch;

    if (Z_STRLEN_P(str) == 0) {
        STR_FREE(Z_STRVAL_P(str));
        Z_STRVAL_P(str) = estrndup("1", sizeof("1")-1);
        Z_STRLEN_P(str) = 1;
        return;
    }

    if (IS_INTERNED(s)) {
        s = (char*) emalloc(Z_STRLEN_P(str) + 1);
        memcpy(s, Z_STRVAL_P(str), Z_STRLEN_P(str) + 1);
        Z_STRVAL_P(str) = s;
    }

    while (pos >= 0) {
        ch = s[pos];
        if (ch >= 'a' && ch <= 'z') {
            if (ch == 'z') {
                s[pos] = 'a';
                carry=1;
            } else {
                s[pos]++;
                carry=0;
            }
            last=LOWER_CASE;
        } else if (ch >= 'A' && ch <= 'Z') {
            if (ch == 'Z') {
                s[pos] = 'A';
                carry=1;
            } else {
                s[pos]++;
                carry=0;
            }
            last=UPPER_CASE;
        } else if (ch >= '0' && ch <= '9') {
            if (ch == '9') {
                s[pos] = '0';
                carry=1;
            } else {
                s[pos]++;
                carry=0;
            }
            last = NUMERIC;
        } else {
            carry=0;
            break;
        }
        if (carry == 0) {
            break;
        }
        pos--;
    }

    if (carry) {
        t = (char *) emalloc(Z_STRLEN_P(str)+1+1);
        memcpy(t+1, Z_STRVAL_P(str), Z_STRLEN_P(str));
        Z_STRLEN_P(str)++;
        t[Z_STRLEN_P(str)] = '\0';
        switch (last) {
            case NUMERIC:
                t[0] = '1';
                break;
            case UPPER_CASE:
                t[0] = 'A';
                break;
            case LOWER_CASE:
                t[0] = 'a';
                break;
        }
        STR_FREE(Z_STRVAL_P(str));
        Z_STRVAL_P(str) = t;
    }
}
/* }}} */
Run Code Online (Sandbox Code Playgroud)

  • 这是从[increment_function()](http://svn.php.net/viewvc/php/php-src/trunk/Zend/zend_operators.c?view=markup#l1790)调用的,我想这是增量运营商. (3认同)