PHP str_ends_with() Function
The PHP str_ends_with() function is used to check if a string ends with a given substring. It performs case-sensitive check and returns true if the string ends with specified substring, else returns false.
Note: It is a binary-safe function. This function is new in PHP 8.
Syntax
str_ends_with(str1, str2)
Parameters
str1 |
Required. Specify the string to search in. |
str2 |
Required. Specify the substring to search in str1. |
Return Value
Returns true if str1 ends with str2, else returns false.
Example:
In the example below, str_ends_with() function is used to check whether the given string ends with specified substring or not.
<?php $str1 = "Hello"; //checking whether $str1 ends with empty string if(str_ends_with($str1, "")) { echo "Every string ends with an empty string.\n"; } //checking whether $str1 ends with "lo" if(str_ends_with($str1, "lo")) { echo "$str1 ends with 'lo'.\n"; } ?>
The output of the above code will be:
Every string ends with an empty string. Hello ends with 'lo'.
Example:
Consider one more example which illustrates on case-sensitive check using str_ends_with() function.
<?php $str = "Hello John"; //checking whether $str ends with "JOHN" if(str_ends_with($str, "JOHN")) { echo 'The string ends with "JOHN".'; } else { echo 'The string does not end with "JOHN". '; echo "\nCase does not match."; } ?>
The output of the above code will be:
The string does not end with "JOHN". Case does not match.
❮ PHP String Reference