牛牛在线工具

str_ends_with()

收录 8868 个 PHP 函数,含用途说明与用法示例。

str_ends_with()

判断一个字符串是否以指定的后缀结尾

函数名: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() 可以提供更简洁和高效的方式来判断一个字符串是否以指定的后缀结尾。