strpos() 是 PHP 中的一个内置函数,用于查找字符串中某个子串首次出现的位置,如果找到子串,则返回子串在字符串中的开始位置;如果没有找到,则返回 false

PHP函数指南:strposPHP函数指南:strpos(图片来源网络,侵删)

语法:

strpos(string $haystack, string $needle, int $offset = 0): int|false

参数说明:

$haystack (必需):要在其中查找子串的字符串。

$needle (必需):要查找的子串。

$offset (可选):从字符串的哪个位置开始查找,默认值为 0。

返回值:

如果找到子串,则返回子串在字符串中的开始位置(整数)。

如果没有找到子串,则返回 false

示例代码:

<?php
$haystack = "Hello, world!";
$needle = "world";
$position = strpos($haystack, $needle);
if ($position !== false) {
    echo "The position of '{$needle}' in '{$haystack}' is: {$position}";
} else {
    echo "'{$needle}' not found in '{$haystack}'";
}
?>

输出结果:

The position of 'world' in 'Hello, world!' is: 7

注意事项:

strpos() 函数对大小写敏感,如果要进行不区分大小写的搜索,可以使用 stripos() 函数。

$offset 参数大于等于 $haystack 的长度,strpos() 函数将返回 false

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。