函式名稱:str_starts_with()
函式功能:判斷一個字串是否以指定的字首開始。
適用版本:PHP 8.0.0 及以上版本。
語法:bool str_starts_with ( string $haystack , string $needle )
引數:
- $haystack:要檢查的字串。
- $needle:要查詢的字首。
返回值:
- 如果 $haystack 字串以 $needle 字首開始,則返回 true。
- 如果 $haystack 字串不以 $needle 字首開始,則返回 false。
示例:
$haystack = "Hello, world!";
$needle = "Hello";
if (str_starts_with($haystack, $needle)) {
echo "字串以指定字首開始";
} else {
echo "字串不以指定字首開始";
}
輸出:
字串以指定字首開始
注意事項:
- 該函式是區分大小寫的,即字首必須與字串的開始部分完全匹配。
- 如果 $needle 是空字串,則該函式將始終返回 true。
- 在 PHP 8.0.0 之前的版本中,可以使用 substr() 函式來實現類似的功能。例如:
substr($haystack, 0, strlen($needle)) === $needle
。