What is PHP str_ends_with() Function?
If you want to check whether a string ends with a specific sub string, use PHP str_ends_with() function.
Syntax:
str_ends_with(string, sub_string)
Parameters:
The Function has 2 required parameters-
string (Required): It specifies a string where you’ll look for the 2nd parameter (sub string).sub_string (Optional): It specifies the sub string that you’ll look for in the 1st parameter (string).
Return Values:
The function returns-
- TRUE – if the sub string found at the end in the string.
- FALSE – if the sub string not found at the end in the string.
Examples:
Example 1:
<?php
$string = "Learn OOP from Schools of web";
$sub_string = "Schools of web";
echo str_ends_with($string, $sub_string) ? "$sub_string FOUND at the end of the string." : "$sub_string NOT FOUND at the end of the string.";
?>
Output:
Schools of web FOUND at the end of the string.
Example 2:
<?php
$string = "Learn MVC from Schools of web";
$sub_string = "schools of web";
echo str_ends_with($string, $sub_string) ? "$sub_string FOUND at the end of the string." : "$sub_string NOT FOUND at the end of the string.";
?>
Output:
schools of web NOT FOUND at the end of the string.
Example 3:
<?php
$string = "Learn CSS from Schools of web";
$sub_string = "";
echo str_ends_with($string, $sub_string) ? "The sub string FOUND at the end of the string." : "The sub string NOT FOUND at the end of the string.";
?>
Output:
The sub string FOUND at the end of the string.
Example 4:
<?php
$string = "Learn MVC from Schools of web";
$sub_string = "Schools of \x77eb";
echo str_ends_with($string, $sub_string) ? "$sub_string FOUND at the end of the string." : "$sub_string NOT FOUND at the end of the string.";
?>
Output:
Schools of web FOUND at the end of the string.
Explanation:
\x77 is a hexadecimal which is equivalent to lowercase “b”.
Notes on str_ends_with() Function:
- It matches in case-sensitive manner which means it differentiates capital and small letters. Check example 2.
- The function always returns TRUE (meaning found) if the word or substring that you use to search is empty as a string always ends with an empty string. Check example 3.
- The function is binary-safe. That means can work correctly on a string that contains binary data. Check example 4.
- As the function was introduced in PHP 8.0, if you want use the previous PHP version, you can use substr() function or substr_compare() function.
PHP Version Support:
PHP 8
Summary: PHP str_ends_with() Function
str_ends_with() function is one of the built-in string functions. It is a very easy and effective way to find a substring in a string.