在開發過程中,常常需要判斷一個字符串是否包含另外一個字符串。PHP提供了多個函數可以實現這個功能,本文將從多個方面對PHP判斷字符串是否存在某個字符串做出詳細的闡述。
一、strpos函數
PHP的strpos函數可以用來在一個字符串中查找另一個字符串第一次出現的位置。函數原型如下:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
其中,haystack參數為要搜索的字符串,needle參數為要查找的字符串,offset參數為起始搜索位置。
如果找到了要查找的字符串,strpos函數將返回它在原字符串中首次出現的位置(位置從0開始數)。如果沒找到,則返回false。
以下是一個例子:
$mystring = 'hello world'; $findme = 'world'; $pos = strpos($mystring, $findme); if ($pos !== false) { echo "字符串 '$findme' 在字符串 '$mystring' 中被發現"; echo "它在字符串 $mystring 的位置是 $pos
";} else { echo '抱歉,沒有找到字符串。';}
上述代碼的輸出結果為:
字符串 ‘world’ 在字符串 ‘hello world’ 中被發現
它在字符串 hello world 的位置是 6
二、preg_match函數
PHP的preg_match函數可以用來在一個字符串中查找符合正則表達式的子字符串。函數原型如下:
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
其中,pattern參數為正則表達式,subject參數為要搜索的字符串,matches參數為存儲匹配結果的數組,flags參數用於指定搜索選項,offset參數為起始搜索位置。
如果找到了符合正則表達式的子字符串,preg_match函數將返回1,否則返回0。
以下是一個例子:
$mystring = 'hello world'; $findme = 'world'; if (preg_match("/$findme/i", $mystring)) { echo "字符串 '$findme' 在字符串 '$mystring' 中被發現"; } else { echo "抱歉,沒有找到字符串。"; }
上述代碼的輸出結果為:
字符串 ‘world’ 在字符串 ‘hello world’ 中被發現
三、substr_count函數
PHP的substr_count函數可以用來計算一個字符串中另一個字符串出現的次數。函數原型如下:
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
其中,haystack參數為要搜索的字符串,needle參數為要查找的字符串,offset參數為起始搜索位置,length參數為要搜索的字符數。
substr_count函數返回的是子字符串在原字符串中出現的次數,如果子字符串沒有出現,則返回0。
以下是一個例子:
$mystring = 'hello world'; $findme = 'l'; echo substr_count($mystring, $findme);
上述代碼的輸出結果為:
3
四、stripos函數
PHP的stripos函數與strpos函數類似,不同的是它是不區分大小寫的。函數原型如下:
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
其中,haystack參數為要搜索的字符串,needle參數為要查找的字符串,offset參數為起始搜索位置。
如果找到了要查找的字符串,stripos函數將返回它在原字符串中首次出現的位置(位置從0開始數)。如果沒找到,則返回false。
以下是一個例子:
$mystring = 'Hello World'; $findme = 'world'; $pos = stripos($mystring, $findme); if ($pos !== false) { echo "字符串 '$findme' 在字符串 '$mystring' 中被發現"; echo "它在字符串 $mystring 的位置是 $pos
";} else { echo '抱歉,沒有找到字符串。';}
上述代碼的輸出結果為:
字符串 ‘world’ 在字符串 ‘Hello World’ 中被發現
它在字符串 Hello World 的位置是 6
五、stristr函數
PHP的stristr函數與stripos函數類似,不同的是它返回的是從第一次出現的位置開始到字符串末尾的所有字符。函數原型如下:
string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
其中,haystack參數為要搜索的字符串,needle參數為要查找的字符串,before_needle參數用於指定返回的子字符串中是否包含needle字符串。
如果找到了要查找的字符串,stristr函數將返回它在原字符串中首次出現的位置開始到字符串末尾的所有字符。如果沒找到,則返回false。
以下是一個例子:
$email = 'USER@EXAMPLE.com'; echo stristr($email, 'e'); // 輸出 EXAMPLE.com echo stristr($email, 'e', true); // 輸出 US
上述代碼的輸出結果為:
EXAMPLE.com
US
原創文章,作者:AJTU,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/136253.html