當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP strpos()用法及代碼示例

strops() 是 PHP 的內置函數。它用於查找字符串在另一個字符串或子字符串中第一次出現的位置。

用法:

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] );
參數 描述 必需/可選
string 指定要搜索的字符串。 Start
find 指定要查找的字符串。 Required
start 指定從何處開始搜索。 Optional

此函數將幫助我們找到 haystack 字符串中第一個出現的 pin 的數字位置

注意:strops() 函數區分大小寫和二進製安全。

例子1

<?php
  $str1="Hello Php";
    $str2="Hello Php javatpoint!";
    echo "First string is:".$str1;
    echo "<br>";
    echo "First string is:".$str2;
    echo "<br>";
    echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
    //$str1 and $str2 'Php'first letter is upper case so output is nothing.
    // It is case-sensitive
?>

輸出:

First string is:Hello Php
First string is:Hello Php javatpoint!
By using 'strpos()' function:

例子2

<?php
    $str1="Hello php";
    $str2=" Hello php javatpoint!";
    echo "First string is:".$str1;
    echo "<br>";
    echo "First string is:".$str2;
    echo "<br>";
    echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
    //Find the position of the first occurrence of "php" inside the string
?>

輸出:

First string is:Hello php
First string is:Hello php javatpoint!
By using 'strpos()' function:6

例子3

<?php
$mystring = 'Hello PHP';
$findme   = 'Hello';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'Hello' was the 0th (first) character.
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 "<br>";
    echo " and exists at position $pos";
}
?>

輸出:

The string 'Hello' was found in the string 'Hello PHP'
and exists at position 0

另見:

strchr():用於查找一個字符串在另一個字符串中的第一次出現。

stscroll():它是基於語言環境的字符串比較。

strcmp():二進製安全字符串比較。

參考:

http://php.net/manual/en/function.strpos.php







相關用法


注:本文由純淨天空篩選整理自 PHP strpos() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。