当前位置: 首页> 函数类别大全> 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编码一个字符串
  • 在字符串中查找一组字符的任何一个字符-返回一个以找到的字符开始的子字符串 strpbrk

    strpbrk

    在字符串中查找一组字符的任何一个字符-返
  • 转换字符串第一个字节为 0-255 之间的值 ord

    ord

    转换字符串第一个字节为0-255之间的值
  • 使用另一个字符串将字符串填充到某个长度 str_pad

    str_pad

    使用另一个字符串将字符串填充到某个长度
  • 返回有关字符串中使用的字符的信息-统计 string 中每个字节值(0..255)出现的次数 count_chars

    count_chars

    返回有关字符串中使用的字符的信息-统计s
  • 使用“自然顺序”算法比较字符串(不区分大小写) strnatcasecmp

    strnatcasecmp

    使用“自然顺序”算法比较字符串(不区分大
  • 从字符串中删除 HTML和PHP标记 strip_tags

    strip_tags

    从字符串中删除HTML和PHP标记
  • 将格式化后的字符串写入到流 fprintf

    fprintf

    将格式化后的字符串写入到流
热门文章