str_ends_with
Check if the string ends with the given substring
Function name: str_ends_with()
Applicable version: PHP 8.0.0 or higher
Function function: determine whether a string ends with the specified suffix.
Syntax: bool str_ends_with ( string $haystack , string $needle )
parameter:
Return value:
Example:
$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 结尾"; }
Output:
Hello, World! 以World! 结尾Hello, PHP! 不以World! 结尾
Note: In versions prior to PHP 8.0.0, similar functionality can be used with the following code:
function str_ends_with($haystack, $needle) { $length = strlen($needle); if ($length == 0) { return true; } return substr($haystack, -$length) === $needle; }
However, using the built-in function str_ends_with() of PHP 8.0.0 and later provides a more concise and efficient way to determine whether a string ends with a specified suffix.