php stripos 字符串查找函数内部源码实现

stripos的内部实现代码和strpos是一样的,只是多了两步内存的操作和转换小写的操作,注意这个地方和strripos函数稍微有点不一样,strripos函数会对搜索的字符是否是一个字符进行判断,如果是一个字符,那么strripos函数是不进行内存的复制,转换成小写后就开始判断,而stripos则没有做是否是一个字符的判断,直接对原字符串进行内存的拷贝。

/* {{{ proto int stripos(string haystack, string needle [, int offset])
   Finds position of first occurrence of a string within another, case insensitive */
PHP_FUNCTION(stripos)
{
    char *found = NULL;
    char *haystack;
    int haystack_len;
    long offset = 0;
    char *needle_dup = NULL, *haystack_dup;
    char needle_char[2];
    zval *needle;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|l", &haystack, &haystack_len, &needle, &offset) == FAILURE) {
        return;
    }

    if (offset < 0 || offset > haystack_len) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Offset not contained in string");
        RETURN_FALSE;
    }

    if (haystack_len == 0) {
        RETURN_FALSE;
    }

   /* 申请内存操作 */
    haystack_dup = estrndup(haystack, haystack_len);

   /* 转换成小写操作 */
    php_strtolower(haystack_dup, haystack_len);

    if (Z_TYPE_P(needle) == IS_STRING) {
        if (Z_STRLEN_P(needle) == 0 || Z_STRLEN_P(needle) > haystack_len) {
            efree(haystack_dup);
            RETURN_FALSE;
        }

        /* 申请内存操作 */
        needle_dup = estrndup(Z_STRVAL_P(needle), Z_STRLEN_P(needle));

        /* 转换成小写操作 */
        php_strtolower(needle_dup, Z_STRLEN_P(needle));
        found = php_memnstr(haystack_dup + offset, needle_dup, Z_STRLEN_P(needle), haystack_dup + haystack_len);
    } else {
        if (php_needle_char(needle, needle_char TSRMLS_CC) != SUCCESS) {
            efree(haystack_dup);
            RETURN_FALSE;
        }
        needle_char[0] = tolower(needle_char[0]);
        needle_char[1] = '\0';
        found = php_memnstr(haystack_dup + offset,
                            needle_char,
                            sizeof(needle_char) - 1,
                            haystack_dup + haystack_len);
    }

    efree(haystack_dup);
    if (needle_dup) {
        efree(needle_dup);
    }

    if (found) {
        RETURN_LONG(found - haystack_dup);
    } else {
        RETURN_FALSE;
    }
}
/* }}} */

所以如果使用此函数进行字符串查找的话,尽可能不要使用太长的字符串,否则会消耗掉很多内存。

疑问的地方是:为什么不先做haystack_len和Z_STRLEN_P(needle)长度的判断,然后再申请内存呢?

注释:haystack_len为原始字符串的长度,Z_STRLEN_P(needle)是需要查找的needle的字符串长度。

转载于:https://my.oschina.net/u/435872/blog/134520

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值