php查找字符串首次出現的位置 判斷字符串是否在另一個字符串中


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

說明

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

返回 needle 在 haystack 中首次出現的數字位置。與 strrpos() 不同,在 PHP 5 之前,該函數可以使用一個完整字符串作為 needle,並且整個字符串都將被使用。

參數

 

haystack

在該字符串中進行查找。

needle

如果 needle 不是一個字符串,那么它將被轉換為整型並被視為字符的順序值。

offset

可選的 offset 參數可以用來指定從 haystack 中的哪一個字符開始查找。返回的數字位置是相對於 haystack 的起始位置而言的。

 

返回值

以整型返回位置信息。如果沒找到 needlestrpos() 將返回布爾型的 FALSE 值。

Warning

此函數可能返回布爾值 FALSE,但也可能返回等同於 FALSE 的非布爾值,例如 0 或 ""(空串)。請閱讀 布爾類型章節以獲取更多信息。應使用 === 運算符 來測試此函數的返回值。

范例

 

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此函數可安全用於二進制對象。

參見

 

    • strrpos() - 計算指定字符串在目標字符串中最后一次出現的位置
    • stripos() - 查找字符串首次出現的位置(不區分大小寫)
    • strripos() - 計算指定字符串在目標字符串中最后一次出現的位置(不區分大小寫)
    • strrchr() - 查找指定字符在字符串中的最后一次出現
    • substr() - 返回字符串的子串
    • stristr() - strstr 函數的忽略大小寫版本
    • strstr() - 查找字符串的首次出現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM