首頁  >  文章  >  後端開發  >  php查詢字串的方法有哪些

php查詢字串的方法有哪些

青灯夜游
青灯夜游原創
2021-06-10 17:23:0713179瀏覽

查詢方法:1、使用stripos(),查詢字串首次出現的位置;2、使用strpos(),查詢字串首次出現的位置;3、使用strripos(),查詢字串最後一次出現的位置;4、使用strrpos(),查詢字串最後一次出現的位置。

php查詢字串的方法有哪些

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

在 PHP 中,可以使用以下4個函數來查找字串。

1、使用stripos()函數

stripos() 用來找出字串中某部分字串首次出現的位置(不區分大小寫)。

語法如下:

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

參數說明如下:

  • #haystack:在該字串中尋找。

  • needle:needle 可以是一個單字元或多重字元的字串。如果 needle 不是一個字串,那麼它將被轉換為整數並被視為字元順序值。

  • offset:可選的 offset 參數允許你指定從 haystack 中的哪個字元開始查找,傳回的位置數字值仍然相對於 haystack 的起始位置。

傳回 needle 存在於 haystack 字串開始的位置(獨立於偏移)。同時注意字串位置起始於 0,而不是 1。如果未發現 needle 就將回傳 false。

範例如下:

<?php
$findme = &#39;c&#39;;
$mystring1 = &#39;xyz&#39;;
$mystring2 = &#39;ABC&#39;;
$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);
var_dump($pos1);
var_dump($pos2);
?>

執行結果為:

bool(false) int(2)

2、使用strpos()函數

strpos() 用來查找字串首次出現的位置。

語法如下:

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

strpos() 和 strrpos()、strripos() 不一樣,strpos 的偏移量不能是負數。

範例如下:

<?php
$findme = &#39;c&#39;;
$findme1 = &#39;C&#39;;
$mystring = &#39;ABCabc&#39;;
$pos1 = strpos($mystring, $findme);
$pos2 = strpos($mystring, $findme1);
var_dump($pos1);
var_dump($pos2);
?>

上述程式碼的執行結果為:

int(5)int(2)

3、使用strripos()函數

strripos () 用來計算指定字串在目標字串中最後一次出現的位置(不區分大小寫)。

語法如下:

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

負數偏移量將使得查找從字串的起始位置開始,到 offset 位置為止。

範例如下:

<?php
$findme = &#39;c&#39;;
$findme1 = &#39;C&#39;;
$mystring = &#39;ABCabcabcABC&#39;;
$pos1 = strripos($mystring, $findme);
$pos2 = strripos($mystring, $findme1);
var_dump($pos1);
var_dump($pos2);
?>

上述程式碼的執行結果為:

int(11)int(11)

4、使用strrpos()函數

strrpos () 用來計算指定字串在目標字串中最後一次出現的位置.

語法如下:

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

如果是負數的偏移量,將會導致查找在字串結尾處開始的計數位置處結束。

範例如下:

<?php
$findme = &#39;c&#39;;
$findme1 = &#39;C&#39;;
$mystring = &#39;ABCabcabcABC&#39;;
$pos1 = strrpos($mystring, $findme);
$pos2 = strrpos($mystring, $findme1);
$pos3 = strrpos($mystring, $findme1,-5);
var_dump($pos1);
var_dump($pos2);
var_dump($pos3);
?>

上述程式碼的執行結果為:

int(8)int(11)int(2)

推薦學習:《PHP影片教學

以上是php查詢字串的方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn