PHP 8 中的 str_starts_with 和 str_ends_with 函式


str_starts_withstr_ends_with 函式已新增到 PHP 8 中,用於檢查給定的字串是否以另一個字串開頭或結尾。如果它以另一個字串開頭並結尾,則返回 true,否則返回 false。

示例

str_starts_with('hello haystack', 'hello'); //starts string found 'True'
str_starts_with('hello haystack', 'stack'); //ends string found 'True'


str_starts_with('hello haystack', 'hay'); //starts string found 'False'
str_starts_with('hello haystack', 'hay'); //ends string found 'False'

PHP 8 中的 str_starts_with() 函式

此函式檢查給定的字串是否以字串 needle 開頭。如果找到第一個字串,則返回 true,否則返回 false。

str_starts_with(string $haystack, string $needle): bool

示例:使用 str_starts_with() 函式。

<?php
   if (str_starts_with('hellohaystack', "hello")) {
      echo "string starts with hello";
   }
?>

輸出

String starts with 'hello'

注意:如果在第二個字串中找不到給定的第一個開頭字串,則返回 false。

PHP 8 中的 str_ends_with() 函式

此函式檢查給定的字串是否以字串 needle 結尾。如果找到給定的字串結尾,則返回 true,否則返回 false。

str_ends_with(string $haystack, string $needle):bool

示例:使用 str_ends_with() 函式

<?php
   if (str_ends_with('hellohaystack', "stack")) {
      echo "string ends with stack";
   }
?>

輸出

String ends with 'stack'

更新於: 2021-04-01

204 閱讀

啟動您的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.