php内置函数分析之strtoupper()、strtolower()

strtoupper():

 1 PHP_FUNCTION(strtoupper)
 2 {
 3     zend_string *str;
 4 
 5     ZEND_PARSE_PARAMETERS_START(1, 1)
 6         Z_PARAM_STR(str)
 7     ZEND_PARSE_PARAMETERS_END();
 8 
 9     RETURN_STR(php_string_toupper(str));
10 }

主要实现在 php_string_toupper()函数:

 1 PHPAPI zend_string *php_string_toupper(zend_string *s)
 2 {
 3     unsigned char *c, *e;
 4 
 5     c = (unsigned char *)ZSTR_VAL(s); //字符串首地址
 6     e = c + ZSTR_LEN(s); // 字符串末尾之后的地址,指向字符串结束标志"\0"
 7 
 8     while (c < e) {
 9         if (islower(*c)) { //遇到第一个小写字符,则进入此if分支,对之后字符的操作都将在此if中完成
10             register unsigned char *r;
11             zend_string *res = zend_string_alloc(ZSTR_LEN(s), 0); //开辟内存存放zend_string类型数据
12 
13             if (c != (unsigned char*)ZSTR_VAL(s)) { //c不是字符串首地址时,执行此if
14                 memcpy(ZSTR_VAL(res), ZSTR_VAL(s), c - (unsigned char*)ZSTR_VAL(s)); //将c位置之前的字符数据复制给res
15             }
16             r = c + (ZSTR_VAL(res) - ZSTR_VAL(s)); // 开始进行转换的位置
17             // 下面的while中对每个字符都执行大写转换操作
18             while (c < e) {
19                 *r = toupper(*c);
20                 r++;
21                 c++;
22             }
23             *r = '\0'; //为字符串添加结束标志
24             return res; //返回新字符串
25         }
26         c++;
27     }
28     return zend_string_copy(s); //原始字符串没有被操作,则返回原始字符串,并将引用+1 
29 }

strtolower()与之类似。

猜你喜欢

转载自www.cnblogs.com/natian-ws/p/9091199.html
今日推荐