(PHP 4, PHP 5, PHP 7, PHP 8)
strpos — 查找字符串首次出現(xiàn)的位置
返回 needle
在 haystack
中首次出現(xiàn)的數(shù)字位置。
haystack
在該字符串中進行查找。
needle
Prior to PHP 8.0.0, if needle
is not a string, it is converted
to an integer and applied as the ordinal value of a character.
This behavior is deprecated as of PHP 7.3.0, and relying on it is highly
discouraged. Depending on the intended behavior, the
needle
should either be explicitly cast to string,
or an explicit call to chr() should be performed.
offset
如果提供了此參數(shù),搜索會從字符串該字符數(shù)的起始位置開始統(tǒng)計。 如果是負數(shù),搜索會從字符串結(jié)尾指定字符數(shù)開始。
返回 needle 存在于 haystack
字符串起始的位置(獨立于 offset)。同時注意字符串位置是從0開始,而不是從1開始的。
如果沒找到 needle,將返回 false
。
版本 | 說明 |
---|---|
7.1.0 |
開始支持負數(shù)的 offset 。
|
示例 #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";
}
?>
示例 #2 使用 !==
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 使用 !== 操作符。使用 != 不能像我們期待的那樣工作,
// 因為 'a' 的位置是 0。語句 (0 != false) 的結(jié)果是 false。
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>
示例 #3 使用位置偏移量
<?php
// 忽視位置偏移量之前的字符進行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>
注意: 此函數(shù)可安全用于二進制對象。