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. The Str::endsWith()
method is, for example, identical to the global ends_with()
function. We are free to use whichever one we prefer in our application.
The following functions return true
or false
values:
The
is
method checks whether a value matches a pattern. The asterisk can be used as a wildcard character:Str::is('projects/*', 'projects/php/'); // Returns true
The
contains
method checks whether a string contains a given substring:Str::contains('Getting Started With Laravel', 'Python'); // returns false
The
startsWith
andendsWith
methods check whether a string starts or ends with one or more substrings:Str::startsWith('.gitignore', '.git'); // Returns true Str::endsWith('index.php', array('html', 'php')); // Returns true
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's fun!"); // Returns "ab-testings-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 = '...')