str_contains
判斷一個字符串中是否包含一個給定的子字符串
函數名稱:str_contains()
函數描述:該函數用於檢查一個字符串是否包含另一個字符串。
適用版本:PHP 8.0.0及以上版本
用法:
bool str_contains ( string $haystack , string $needle )
參數:
$haystack
:要搜索的字符串。$needle
:要搜索的子字符串。返回值:如果$haystack
包含$needle
,則返回true
,否則返回false
。
示例:
$str = "Hello, world!"; $substring = "world"; if (str_contains($str, $substring)) { echo "字符串中包含子字符串"; } else { echo "字符串中不包含子字符串"; }
輸出:
字符串中包含子字符串
注意事項:
str_contains()
函數是區分大小寫的,如果需要進行大小寫不敏感的搜索,可以使用stripos()
函數。strpos()
函數來檢查一個字符串是否包含另一個字符串,但是需要手動判斷返回值是否為false
。在PHP 8.0.0 之後,推薦使用str_contains()
函數,因為它更加簡潔和直觀。