php中利用stripos()获取字符串首次出现的位置?

21次阅读
没有评论

stripos()函数用于在字符串中查找第一次出现的子字符串,并返回其位置。与strpos()函数不同,stripos()函数对大小写不敏感。

具体用法如下:

stripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int|false

其中,$haystack是要查找的字符串,$needle是要查找的子字符串,$offset是从字符串哪个位置开始查找(可选参数)。函数返回所查找的子字符串在$haystack字符串中第一次出现的位置,如果未找到则返回false。

以下是一个示例,展示如何使用stripos()函数:

<?php
$haystack = 'Hello World!';
$needle = 'world';

$position = stripos($haystack, $needle);

if ($position === false) {
    echo "The substring '$needle' was not found in the string '$haystack'";
} else {
    echo "The substring '$needle' was found in the string '$haystack'";
    echo " and exists at position $position";
}
?>

输出结果:

The substring 'world' was found in the string 'Hello World!' and exists at position 6

在上面的示例中,我们首先定义了$haystack和$needle字符串。然后,我们使用stripos()函数查找$needle字符串在$haystack字符串中第一次出现的位置。由于$needle字符串被找到了,$position变量将被赋值为6($needle字符串在$haystack字符串中第一次出现的位置为6)。

接下来,我们使用if语句检查$position变量的值,以确定是否找到了$needle字符串。如果找到了,则在屏幕上显示包含有关此位置的消息的字符串。否则,我们将在屏幕上显示另一条消息,说明未找到这个字符串。

正文完
 
评论(没有评论)