$haystack = "maio290";
$needle = ord("a");
var_dump(strpos($haystack,$needle));
输出:int(1)
为什么?字符的序数值等于您可以在多个 ASCII 表中找到的数字。例如,字符“a”等于整数 97。
这是 PHP 的源代码(或者你需要了解函数 strpos 的东西):
static int php_needle_char(zval *needle, char *target)
{
switch (Z_TYPE_P(needle)) {
case IS_LONG:
*target = (char)Z_LVAL_P(needle);
return SUCCESS;
case IS_NULL:
case IS_FALSE:
*target = '\0';
return SUCCESS;
case IS_TRUE:
*target = '\1';
return SUCCESS;
case IS_DOUBLE:
*target = (char)(int)Z_DVAL_P(needle);
return SUCCESS;
case IS_OBJECT:
*target = (char) zval_get_long(needle);
return SUCCESS;
default:
php_error_docref(NULL, E_WARNING, "needle is not a string or an integer");
return FAILURE;
}
}
PHP_FUNCTION(strpos)
{
zval *needle;
zend_string *haystack;
const char *found = NULL;
char needle_char[2];
zend_long offset = 0;
ZEND_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STR(haystack)
Z_PARAM_ZVAL(needle)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(offset)
ZEND_PARSE_PARAMETERS_END();
if (offset < 0) {
offset += (zend_long)ZSTR_LEN(haystack);
}
if (offset < 0 || (size_t)offset > ZSTR_LEN(haystack)) {
php_error_docref(NULL, E_WARNING, "Offset not contained in string");
RETURN_FALSE;
}
if (Z_TYPE_P(needle) == IS_STRING) {
if (!Z_STRLEN_P(needle)) {
php_error_docref(NULL, E_WARNING, "Empty needle");
RETURN_FALSE;
}
found = (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;
}
needle_char[1] = 0;
php_error_docref(NULL, E_DEPRECATED,
"Non-string needles will be interpreted as strings in the future. " \
"Use an explicit chr() call to preserve the current behavior");
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;
}
}
在这里找到:https ://github.com/php/php-src/blob/master/ext/standard/string.c
这意味着:
long
:获取一个长值并将其转换为字符。
null or false
: 返回 0(作为字符)
true
: 返回 1(作为字符)
double
:获取一个双精度值,将其转换为整数(这意味着点后的所有部分都将丢失),然后将其转换为字符。
object
: 从对象中获取 long (? 并将其转换为 char。
我对 C 或 Zend-Engine 没有那么深入,因此我可能解释了一些错误。但这实际上应该是您正在寻找的。