(PHP 4, PHP 5, PHP 7)
strpos — 查找字符串首次出現的位置
說明
返回 needle
在 haystack
中首次出現的數字位置。
參數
-
haystack
-
在該字符串中進行查找。
-
needle
-
如果
needle
不是一個字符串,那么它將被轉換為整型並被視為字符的順序值。 -
offset
-
如果提供了此參數,搜索會從字符串該字符數的起始位置開始統計。和 strrpos()、 strripos()不一樣,這個偏移量不能是負數。
返回值
返回 needle 存在於 haystack
字符串起始的位置(獨立於 offset)。同時注意字符串位置是從0開始,而不是從1開始的。
如果沒找到 needle,將返回 FALSE
。
范例
Example #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";
}
?>
Example #2 使用 !==
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 使用 !== 操作符。使用 != 不能像我們期待的那樣工作,
// 因為 'a' 的位置是 0。語句 (0 != false) 的結果是 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'";
}
?>
Example #3 使用位置偏移量
<?php
// 忽視位置偏移量之前的字符進行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>
注釋
Note: 此函數可安全用於二進制對象。
參見
- stripos() - 查找字符串首次出現的位置(不區分大小寫)
- strrpos() - 計算指定字符串在目標字符串中最后一次出現的位置
- strripos() - 計算指定字符串在目標字符串中最后一次出現的位置(不區分大小寫)
- strstr() - 查找字符串的首次出現
- strpbrk() - 在字符串中查找一組字符的任何一個字符
- substr() - 返回字符串的子串
- preg_match() - 執行一個正則表達式匹配