当前位置: 首页> 函数类别大全> 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() 可以提供更简洁和高效的方式来判断一个字符串是否以指定的后缀结尾。

同类函数
  • 使用 uuencode 编码一个字符串 convert_uuencode

    convert_uuencode

    使用uuencode编码一个字符串
  • 二进制安全不区分大小写的字符串比较 strcasecmp

    strcasecmp

    二进制安全不区分大小写的字符串比较
  • 查找字符串的首次出现 strstr

    strstr

    查找字符串的首次出现
  • 检查字符串是否以给定的子字符串开头 str_starts_with

    str_starts_with

    检查字符串是否以给定的子字符串开头
  • 计算两个字符串之间的相似性 similar_text

    similar_text

    计算两个字符串之间的相似性
  • 从数字生成单字节字符串 chr

    chr

    从数字生成单字节字符串
  • 将字符串转化为大写 strtoupper

    strtoupper

    将字符串转化为大写
  • 删除字符串末端的空白字符(或者其他字符) rtrim

    rtrim

    删除字符串末端的空白字符(或者其他字符)
热门文章