The string manipulation functions are found in the Illuminate\Support
namespace and are callable on the Str
object.
Most of the functions also have shorter snake_case
aliases. For example, the Str::endsWith()
method is identical to the global ends_with()
function. We are free to use whichever one we prefer in our application.
The following functions return the true
or false
values:
The
is
method checks whether a value matches a pattern. The asterisk can be used as a wildcard character as shown here:Str::is('projects/*', 'projects/php/'); // Returns true
The
contains
method, as shown in the following code, checks whether a string contains a given substring:Str::contains('Getting Started With Laravel', 'Python'); // returns false
The
startsWith
andendsWith
methods, as shown in the following code, check whether a string starts or ends with one or more substrings:Str::startsWith('.gitignore', '.git'); // Returns true Str::endsWith('index.php', ['html', 'php']); // Returns true
As you can see from the preceding examples, these methods are handy for validation filenames and similar data.
In some cases, you need to transform a string before displaying it to the user or using it in a URL. Laravel provides the following helpers to achieve this:
This function generates a URL-friendly string:
Str::slug('A/B testing is fun!'); // Returns "ab-testing-is-fun"
This function generates a title where every word is capitalized:
Str::title('getting started with laravel'); // Returns 'Getting Started With Laravel'
This function caps a string with an instance of a given character:
Str::finish('/one/trailing/slash', '/'); Str::finish('/one/trailing/slash/', '/'); // Both will return '/one/trailing/slash/'
This function limits the number of characters in a string:
Str::limit($value, $limit = 100, $end = '...')
This function limits the number of words in a string:
Str::words($value, $words = 100, $end = '...')
The following functions help you find out the plural or singular form of a word, even if it is irregular:
This function finds out the plural form of a word:
Str::plural('cat'); // Returns 'cats' Str::plural('fish'); // Returns 'fish' Str::plural('monkey'); // Returns 'monkeys'
This function finds out the singular form of a word:
Str::singular('elves'); // Returns 'elf'