概述在PHP中,strpos常用于判断一个字符串是否存在于另一个字符串中。本文介绍strpos函数及其实现。strpos应用程序=4.0.6,PHP5,PHP7strstr查找字符串的第一次出现PHP4,PHP5,PHP7不区分大小写的strstr()函数版本PHP4,PHP5,PHP7substr_count计算字符串的出现次数PHP4,PHP5,PHP7mb*也有相关函数,例如mb_strpos根据字符数进行多字节安全的strpos()操作。PHP(strpos)源代码strpos(ext/standard/string.c)PHP源代码地址PHP_FUNCTION(strpos){zval*needle;zend_string*干草堆;char*found=NULL;字符needle_char[2];zend_longoffset=0;#ifndefFAST_ZPPif(zend_parse_parameters(ZEND_NUM_ARGS(),"Sz|l",&haystack,&needle,&offset)==FAILURE){返回;}#elseZEND_PARSE_PARAMETERS_START(2,3)Z_PARAM_STR(haystack)Z_PARAM_ZVAL(needle)Z_PARAM_OPTIONALZ_PARAM_LONG(offset)ZEND_PARSE_PARAMETERS_END();#endifif(offset<0){offset+=(zend_long)ZSTR_LEN(haystack);}if(offset<0||(size_t)offset>ZSTR_LEN(haystack)){php_error_docref(NULL,E_WARNING,"偏移量不包含在字符串中");返回假;}if(Z_TYPE_P(needle)==IS_STRING){if(!Z_STRLEN_P(needle)){php_error_docref(NULL,E_WARNING,"空针");返回假;}发现=(char*)php_memnstr(ZSTR_VAL(haystack)+offset,Z_STRVAL_P(needle),Z_STRLEN_P(needle),ZSTR_VAL(haystack)+ZSTR_LEN(haystack));}else{if(php_needle_char(needle,needle_char)!=SUCCESS){RETURN_FALSE}need_char;[1]=0;found=(char*)php_memnstr(ZSTR_VAL(haystack)+offset,needle_char,1,ZSTR_VAL(haystack)+ZSTR_LEN(haystack));}if(found){RETURN_LONG(found-ZSTR_VAL(haystack));}else{RETURN_FALSE;}}php_memnstr(main/php.h)PHP源码地址#definephp_memnstrzend_memnstr/*338行*/zend_memnstr(Zend/zend_operators.h)PHP源码地址/**该函数的作用在Searchneedleinhaystack,不存在则返回null,存在则返回指向haystack中needle首字符的指针*/zend_memnstr(constchar*haystack,constchar*needle,size_tneedle_len,constchar*end){constchar*p=干草堆;constcharne=needle[needle_len-1];ptrdiff_toff_p;size_toff_s;如果(needle_len==1){return(constchar*)memchr(p,*needle,(end-p));}off_p=end-haystack;off_s=(off_p>0)?(size_t)off_p:0;如果(needle_len>off_s){返回NULL;}if(EXPECTED(off_s<1024||needle_len<3)){//第一次优化,只搜索end-needle_len次end-=needle_len;while(p<=end){//第二次优化,先判断字符串首尾是否相同再判断整个字符串if((p=(constchar*)memchr(p,*needle,(end-p+1)))&&ne==p[needle_len-1]){if(!memcmp(needle,p,needle_len-1)){返回p;}}if(p==NULL){返回NULL;}p++;}返回空值;}else{returnzend_memnstr_ex(haystack,needle,needle_len,end);}}memchr(string.h)Linux内核版本-源码地址/*头文件:#include
