函式名:strstr()
適用版本:PHP 4, PHP 5, PHP 7
函式描述:strstr()函式用於在字串中查詢指定的子字串,並返回從該子字串開始到字串結尾的部分。如果未找到子字串,則返回false。
語法:strstr(string $haystack, mixed $needle, bool $before_needle = false): string|false
引數:
- haystack:要在其中查詢子字串的字串。
- needle:要查詢的子字串。可以是一個字串或一個陣列。
- before_needle(可選):如果設定為true,則返回needle之前的部分;如果設定為false(預設值),則返回needle之後的部分。
返回值:
- 如果找到了子字串,返回從子字串開始到字串結尾的部分。
- 如果未找到子字串,返回false。
示例:
// 示例1:查詢子字串,並返回從子字串開始到字串結尾的部分
$haystack = "Hello, world!";
$needle = "world";
$result = strstr($haystack, $needle);
echo $result; // 輸出:world!
// 示例2:查詢子字串,並返回子字串之前的部分
$haystack = "Hello, world!";
$needle = ",";
$result = strstr($haystack, $needle, true);
echo $result; // 輸出:Hello
// 示例3:未找到子字串,返回false
$haystack = "Hello, world!";
$needle = "foo";
$result = strstr($haystack, $needle);
var_dump($result); // 輸出:bool(false)
注意事項:
- 該函式區分大小寫,如果需要進行大小寫不敏感的查詢,可以使用stristr()函式。
- 如果needle是一個陣列,函式將對每個元素進行查詢,並返回第一個找到的子字串及其後的部分。
- 從PHP 8.0開始,將不再支援before_needle引數。如果需要返回子字串之前的部分,可以使用substr()函式來實現。