Laravel 5

Checking if a String Ends with a Particular Value in Laravel -Laravel 5.5 String Helper Method: endsWith


John Koster

Published on November 30, 2017

The endsWith is used to check if a given $haystack ends with any of the supplied $needles. The $haystack is any value that can be cast into a string, and $needles is any value that can be cast into an array. If the $haystack ends with any of the $needles, the method returns true. Otherwise, it returns false.


The signature of the endsWith method is:

1public static endsWith(
2 $haystack,
3 $needles
4 );

Example Use

1use Illuminate\Support\Str;
3// true
4Str::endsWith('A simple sentence.', '.');
6// false
7Str::endsWith('No punctuation here', '.');
9// false
10Str::endsWith('Case matters', 'S');
12// true
13Str::endsWith('CASE STILL MATTERS', 'S');

We can combine this with PHP's built in range function for a simple way to check if a string ends in any alphabetical character:

1use Illuminate\Support\Str;
3// First, let's build our alphabet string.
4$alphabet = array_merge(range('a', 'z'), range('A', 'Z'));
6// true
7Str::endsWith('This is a simple string', $alphabet);
9// false
10Str::endsWith('This ends the number 2', $alphabet);

Global ends_with Helper Function

The ends_with function is a shortcut to calling Str::endsWith. This function is declared in the global namespace.