当前位置: 首页> 函数类别大全> str_ends_with

str_ends_with

检查字符串是否以给定的子字符串结尾
名称:str_ends_with
分类:字符串
所属语言:php
一句话介绍: 判断一个字符串是否以指定的后缀结尾

函数名:str_ends_with()

适用版本:PHP 8.0.0 或更高版本

函数功能:判断一个字符串是否以指定的后缀结尾

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

参数:

  • $haystack:要检查的字符串
  • $needle:要检查的后缀

返回值:

  • 如果 $haystack 以 $needle 结尾,则返回 true
  • 如果 $haystack 不以 $needle 结尾,则返回 false

示例:

$string1 = "Hello, World!";
$string2 = "Hello, PHP!";
$suffix = "World!";

// 检查 $string1 是否以 $suffix 结尾
if (str_ends_with($string1, $suffix)) {
    echo "$string1 以 $suffix 结尾";
} else {
    echo "$string1 不以 $suffix 结尾";
}

// 检查 $string2 是否以 $suffix 结尾
if (str_ends_with($string2, $suffix)) {
    echo "$string2 以 $suffix 结尾";
} else {
    echo "$string2 不以 $suffix 结尾";
}

输出:

Hello, World! 以 World! 结尾
Hello, PHP! 不以 World! 结尾

注意:在 PHP 8.0.0 之前的版本中,可以使用类似的功能通过以下代码实现:

function str_ends_with($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return substr($haystack, -$length) === $needle;
}

然而,使用 PHP 8.0.0 及更高版本的内置函数 str_ends_with() 可以提供更简洁和高效的方式来判断一个字符串是否以指定的后缀结尾。

同类函数
  • 检查字符串是否以给定的子字符串结尾 str_ends_with

    str_ends_with

    检查字符串是否以给定的子字符串结尾
  • 从字符串中删除 HTML和PHP标记 strip_tags

    strip_tags

    从字符串中删除HTML和PHP标记
  • 将数字格式化成货币字符串 money_format

    money_format

    将数字格式化成货币字符串
  • 将字符串转换为数组 str_split

    str_split

    将字符串转换为数组
  • 替换字符串的子串 substr_replace

    substr_replace

    替换字符串的子串
  • 标记分割字符串 strtok

    strtok

    标记分割字符串
  • 输出一个或多个字符串 echo

    echo

    输出一个或多个字符串
  • 将字符串拆分为较小的块 chunk_split

    chunk_split

    将字符串拆分为较小的块
热门文章