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