Search

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

November 30, 2017 —John Koster

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.

#Signature

The signature of the endsWith method is:

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

#Example Use

1use Illuminate\Support\Str;
2 
3// true
4Str::endsWith('A simple sentence.', '.');
5 
6// false
7Str::endsWith('No punctuation here', '.');
8 
9// false
10Str::endsWith('Case matters', 'S');
11 
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;
2 
3// First, let's build our alphabet string.
4$alphabet = array_merge(range('a', 'z'), range('A', 'Z'));
5 
6// true
7Str::endsWith('This is a simple string', $alphabet);
8 
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.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.