PHP 8 中的 str_starts_with 和 str_ends_with 函数

phpserver side programmingprogramming更新于 2025/9/15 10:52:17

str_starts_with 和 str_ends_with 函数是 PHP 8 中新增的函数,用于检查给定字符串是否以另一个字符串开头或结尾。如果以另一个字符串开头和结尾,则返回 true,否则返回 false。

示例

str_starts_with('hello haystack', 'hello'); // 起始字符串为 'True'
str_starts_with('hello haystack', 'stack'); // 结束字符串为 'True'
str_starts_with('hello haystack', 'hay'); // 起始字符串为 'False'
str_starts_with('hello haystack', 'hay'); // 结束字符串为 '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'

相关文章