溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

php中怎么查詢字符串

發(fā)布時(shí)間:2021-06-11 09:23:33 來(lái)源:億速云 閱讀:2273 作者:小新 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)php中怎么查詢字符串,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

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

本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦

在 PHP 中,可以使用以下4個(gè)函數(shù)來(lái)查找字符串。

1、使用stripos()函數(shù)

stripos() 用來(lái)查找字符串中某部分字符串首次出現(xiàn)的位置(不區(qū)分大小寫)。

語(yǔ)法如下:

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

參數(shù)說(shuō)明如下:

  • haystack:在該字符串中查找。

  • needle:needle 可以是一個(gè)單字符或者多字符的字符串。如果 needle 不是一個(gè)字符串,那么它將被轉(zhuǎn)換為整型并被視為字符順序值。

  • offset:可選的 offset 參數(shù)允許你指定從 haystack 中的哪個(gè)字符開始查找,返回的位置數(shù)字值仍然相對(duì)于 haystack 的起始位置。

返回 needle 存在于 haystack 字符串開始的位置(獨(dú)立于偏移量)。同時(shí)注意字符串位置起始于 0,而不是 1。如果未發(fā)現(xiàn) needle 就將返回 false。

示例如下:

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

執(zhí)行結(jié)果為:

bool(false) int(2)

2、使用strpos()函數(shù)

strpos() 用來(lái)查找字符串首次出現(xiàn)的位置。

語(yǔ)法如下:

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

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

示例如下:

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

上述代碼的執(zhí)行結(jié)果為:

int(5)int(2)

3、使用strripos()函數(shù)

strripos() 用來(lái)計(jì)算指定字符串在目標(biāo)字符串中最后一次出現(xiàn)的位置(不區(qū)分大小寫)。

語(yǔ)法如下:

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

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

示例如下:

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

上述代碼的執(zhí)行結(jié)果為:

int(11)int(11)

4、使用strrpos()函數(shù)

strrpos() 用來(lái)計(jì)算指定字符串在目標(biāo)字符串中最后一次出現(xiàn)的位置.

語(yǔ)法如下:

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

如果是負(fù)數(shù)的偏移量,將會(huì)導(dǎo)致查找在字符串結(jié)尾處開始的計(jì)數(shù)位置處結(jié)束。

示例如下:

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

上述代碼的執(zhí)行結(jié)果為:

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

關(guān)于“php中怎么查詢字符串”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI