stripos的内部实现代码和strpos是同样的,只是多了两步内存的操做和转换小写的操做,注意这个地方和strripos函数稍微有点不同,strripos函数会对搜索的字符是不是一个字符进行判断,若是是一个字符,那么strripos函数是不进行内存的复制,转换成小写后就开始判断,而stripos则没有作是不是一个字符的判断,直接对原字符串进行内存的拷贝。 php
/* {{{ 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); spa
/* 转换成小写操做 */
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;
} ip
/* 申请内存操做 */
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;
}
}
/* }}} */ 字符串
因此若是使用此函数进行字符串查找的话,尽量不要使用太长的字符串,不然会消耗掉不少内存。 string
疑问的地方是:为何不先作haystack_len和Z_STRLEN_P(needle)长度的判断,而后再申请内存呢? it
注释:haystack_len为原始字符串的长度,Z_STRLEN_P(needle)是须要查找的needle的字符串长度。 io