专栏/PHP之strpos

PHP之strpos

2020年02月06日 16:47--浏览 · --喜欢 · --评论
粉丝:14文章:9

(PHP 4, PHP 5, PHP 7)

strpos — 查找字符串首次出现的位置

说明 

strpos( string $haystack, mixed $needle[, int $offset = 0] ) : int

返回 needle 在 haystack 中首次出现的数字位置。 mixed 是混合型,数字,ascll码,字符串都可以找,比如输入97可能回找到a

参数 

haystack

在该字符串中进行查找。 

needle

如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。 

offset(偏移量)

如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。如果是负数,搜索会从字符串结尾指定字符数开始。 

<?php

// 忽视位置偏移量之前的字符进行查找

$newstring = 'abcdef abcdef';

$pos = strpos($newstring, 'a', 1);

echo $pos;

 // $pos = 7, 不是 0

?> 

----------------------------------------------

<?php

// 忽视位置偏移量之前的字符进行查找

$newstring = 'abcdef abcdef';

$pos = strpos($newstring, 'abc', 3);

echo $pos;

 // $pos = 7, 不是 0

?>

/*


*/






返回值 


返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始,而不是从1开始的。 如果没找到 needle,将返回 FALSE。 

> Warning 此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。


例子1

<?php

$mystring = 'abc';

$findme   = 'a';

$pos = strpos($mystring, $findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,

// 因为 'a' 是第 0 位置上的(第一个)字符。

if ($pos === false) {

    echo "The string '$findme' was not found in the string '$mystring'";

} else {

    echo "The string '$findme' was found in the string '$mystring'";

    echo " and exists at position $pos";

}

?> 


因为strpos返回值是int型,只有找不到字符串时是Flase,当不用===时,0会被当成Flase来执行,所以第0个字符不被输出


参考手册


投诉或建议