Laravel 5 String Helpers: Uppercasing the First Word of a Value

Laravel 5

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:

public static endsWith(
        $haystack,
        $needles
    );

Example Use

use Illuminate\Support\Str;

// true
Str::endsWith('A simple sentence.', '.');

// false
Str::endsWith('No punctuation here', '.');

// false
Str::endsWith('Case matters', 'S');

// true
Str::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:

use Illuminate\Support\Str;

// First, let's build our alphabet string.
$alphabet = array_merge(range('a', 'z'), range('A', 'Z'));

// true
Str::endsWith('This is a simple string', $alphabet);

// false
Str::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.

Start the Discussion

Leave a comment

Subscribe to our newsletter