This article demonstrates how to implement the ends_with() function in PHP.

1. Using strrpos() function

The best option to implement the ends_with() function in PHP is using the strrpos() function. It returns the position of the last occurrence of a substring within a string, where the search starts from the specified offset. For example,

Download  Run Code

 
Alternatively, you can use the strpos() function to implement the ends_with() function, which returns the index of the first occurrence of a substring in a string. To match the last occurrence, you can limit the search space using the offset parameter.

Download  Run Code

 
Note: You can make the search case-insensitive using the stripos() and strripos() functions.

2. Using substr() function

The idea is to find the substring length, chop that many characters from the string’s end, and compare the resultant string with the substring. This can be easily done with the substr() function with a negative offset and length omitted, which extracts a substring from the string’s end. The following code example provides a demonstration.

Download  Run Code

 
Note: This works, but strpos() function is a faster and more memory-efficient option.

3. Using substr_compare() function

Another alternative is to use the substr_compare() function to implement the ends_with() function. It performs a comparison between two strings, starting from an offset, and returns 0 if both strings are equal. To make the comparison case-insensitive, you can pass the substring’s length as the fourth parameter and set the fifth parameter to true.

Download  Run Code

4. Using preg_match() function

Finally, you can use a regex to determine whether a string ends with a substring or not. In PHP, the preg_match() function takes a regex, and returns 1 if and only if the pattern matches the string. This can be used as follows:

Download  Run Code

 
Here, $ matches with the end of a string. Since preg_match() function returns false on failure, the use of === operator is preferred. To make the search case-insensitive, you can append i to the pattern, i.e., "/{$suffix}$/i".

That’s all about implementing the ends_with() function in PHP.