Skip to content

Instantly share code, notes, and snippets.

@shaedrich
Last active September 21, 2023 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaedrich/fb6c29016361db03736fa4541858e3d3 to your computer and use it in GitHub Desktop.
Save shaedrich/fb6c29016361db03736fa4541858e3d3 to your computer and use it in GitHub Desktop.
Laravel Docs > Digging Deeper > Strings (\Illuminate\Support\Str)

Strings

Introduction

Laravel includes a variety of functions for manipulating string values. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

Translators

__() {.collection-method}

The __ function translates the given translation string or translation key using your language files:

echo __('Welcome to our application');

echo __('messages.welcome');

If the specified translation string or key does not exist, the __ function will return the given value. So, using the example above, the __ function would return messages.welcome if that translation key does not exist.

Templates

e() {.collection-method}

The e function runs PHP's htmlspecialchars function with the double_encode option set to true by default:

echo e('<html>foo</html>');

// &lt;html&gt;foo&lt;/html&gt;

Casing

Str::camel()/StrCase::camel() {.collection-method}

Static method ✓ • Instance method ✓ • Global function ×

The Str::camel method converts the given string to camelCase:

use Illuminate\Support\Str;

$converted = Str::camel('foo_bar'); // or Str::of('foo_bar')->camel();

// fooBar

Str::headline()/StrCase::headline() {.collection-method}

The Str::headline method will convert strings delimited by casing, hyphens, or underscores into a space delimited string with each word's first letter capitalized:

use Illuminate\Support\Str;

$headline = Str::headline('steve_jobs');

// Steve Jobs

$headline = Str::headline('EmailNotificationSent');

// Email Notification Sent

Str::kebab()/StrCase::kebab() {.collection-method}

The Str::kebab method converts the given string to kebab-case:

use Illuminate\Support\Str;

$converted = Str::kebab('fooBar'); // or Str::of('fooBar')->kebab();

// foo-bar

Generators

Str::random()/StrGen::random() {.collection-method}

The Str::random method generates a random string of the specified length. This function uses PHP's random_bytes function:

use Illuminate\Support\Str;

$random = Str::random(40);

Str::orderedUuid()/StrGen::orderedUuid() {.collection-method}

The Str::orderedUuid method generates a "timestamp first" UUID that may be efficiently stored in an indexed database column. Each UUID that is generated using this method will be sorted after UUIDs previously generated using the method:

use Illuminate\Support\Str;

return (string) Str::orderedUuid();

Str::uuid()/StrGen::uuid() {.collection-method}

The Str::uuid method generates a UUID (version 4):

use Illuminate\Support\Str;

return (string) Str::uuid();

Other

class_basename() {.collection-method}

The class_basename function returns the class name of the given class with the class's namespace removed:

$class = class_basename('Foo\Bar\Baz');

// Baz

preg_replace_array() {.collection-method}

The preg_replace_array function replaces a given pattern in the string sequentially using an array:

$string = 'The event will take place between :start and :end';

$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);

// The event will take place between 8:30 and 9:00

Str::after() {.collection-method}

The Str::after method returns everything after the given value in a string. The entire string will be returned if the value does not exist within the string:

use Illuminate\Support\Str;

$slice = Str::after('This is my name', 'This is');

// ' my name'

Str::afterLast() {.collection-method}

The Str::afterLast method returns everything after the last occurrence of the given value in a string. The entire string will be returned if the value does not exist within the string:

use Illuminate\Support\Str;

$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');

// 'Controller'

Str::ascii() {.collection-method}

The Str::ascii method will attempt to transliterate the string into an ASCII value:

use Illuminate\Support\Str;

$slice = Str::ascii('û');

// 'u'

Str::before() {.collection-method}

The Str::before method returns everything before the given value in a string:

use Illuminate\Support\Str;

$slice = Str::before('This is my name', 'my name');

// 'This is '

Str::beforeLast() {.collection-method}

The Str::beforeLast method returns everything before the last occurrence of the given value in a string:

use Illuminate\Support\Str;

$slice = Str::beforeLast('This is my name', 'is');

// 'This '

Str::between() {.collection-method}

The Str::between method returns the portion of a string between two values:

use Illuminate\Support\Str;

$slice = Str::between('This is my name', 'This', 'name');

// ' is my '

Str::betweenFirst() {.collection-method}

The Str::betweenFirst method returns the smallest possible portion of a string between two values:

use Illuminate\Support\Str;

$slice = Str::betweenFirst('[a] bc [d]', '[', ']');

// 'a'

Str::contains() {.collection-method}

The Str::contains method determines if the given string contains the given value. This method is case sensitive:

use Illuminate\Support\Str;

$contains = Str::contains('This is my name', 'my');

// true

You may also pass an array of values to determine if the given string contains any of the values in the array:

use Illuminate\Support\Str;

$contains = Str::contains('This is my name', ['my', 'foo']);

// true

Str::containsAll() {.collection-method}

The Str::containsAll method determines if the given string contains all of the values in a given array:

use Illuminate\Support\Str;

$containsAll = Str::containsAll('This is my name', ['my', 'name']);

// true

Str::endsWith() {.collection-method}

The Str::endsWith method determines if the given string ends with the given value:

use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', 'name');

// true

You may also pass an array of values to determine if the given string ends with any of the values in the array:

use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', ['name', 'foo']);

// true

$result = Str::endsWith('This is my name', ['this', 'foo']);

// false

Str::excerpt() {.collection-method}

The Str::excerpt method extracts an excerpt from a given string that matches the first instance of a phrase within that string:

use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'my', [
    'radius' => 3
]);

// '...is my na...'

The radius option, which defaults to 100, allows you to define the number of characters that should appear on each side of the truncated string.

In addition, you may use the omission option to define the string that will be prepended and appended to the truncated string:

use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]);

// '(...) my name'

Str::finish() {.collection-method}

The Str::finish method adds a single instance of the given value to a string if it does not already end with that value:

use Illuminate\Support\Str;

$adjusted = Str::finish('this/string', '/');

// this/string/

$adjusted = Str::finish('this/string/', '/');

// this/string/

Str::inlineMarkdown() {.collection-method}

The Str::inlineMarkdown method converts GitHub flavored Markdown into inline HTML using CommonMark. However, unlike the markdown method, it does not wrap all generated HTML in a block-level element:

use Illuminate\Support\Str;

$html = Str::inlineMarkdown('**Laravel**');

// <strong>Laravel</strong>

Str::is() {.collection-method}

The Str::is method determines if a given string matches a given pattern. Asterisks may be used as wildcard values:

use Illuminate\Support\Str;

$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

Str::isAscii() {.collection-method}

The Str::isAscii method determines if a given string is 7 bit ASCII:

use Illuminate\Support\Str;

$isAscii = Str::isAscii('Taylor');

// true

$isAscii = Str::isAscii('ü');

// false

Str::isJson() {.collection-method}

The Str::isJson method determines if the given string is valid JSON:

use Illuminate\Support\Str;

$result = Str::isJson('[1,2,3]');

// true

$result = Str::isJson('{"first": "John", "last": "Doe"}');

// true

$result = Str::isJson('{first: "John", last: "Doe"}');

// false

Str::isUrl() {.collection-method}

The Str::isUrl method determines if the given string is a valid URL:

use Illuminate\Support\Str;

$isUrl = Str::isUrl('http://example.com');

// true

$isUrl = Str::isUrl('laravel');

// false

Str::isUlid() {.collection-method}

The Str::isUlid method determines if the given string is a valid ULID:

use Illuminate\Support\Str;

$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');

// true

$isUlid = Str::isUlid('laravel');

// false

Str::isUuid() {.collection-method}

The Str::isUuid method determines if the given string is a valid UUID:

use Illuminate\Support\Str;

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

Str::lcfirst() {.collection-method}

The Str::lcfirst method returns the given string with the first character lowercased:

use Illuminate\Support\Str;

$string = Str::lcfirst('Foo Bar');

// foo Bar

Str::length() {.collection-method}

The Str::length method returns the length of the given string:

use Illuminate\Support\Str;

$length = Str::length('Laravel');

// 7

Str::limit() {.collection-method}

The Str::limit method truncates the given string to the specified length:

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox...

You may pass a third argument to the method to change the string that will be appended to the end of the truncated string:

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

Str::lower() {.collection-method}

The Str::lower method converts the given string to lowercase:

use Illuminate\Support\Str;

$converted = Str::lower('LARAVEL');

// laravel

Str::markdown() {.collection-method}

The Str::markdown method converts GitHub flavored Markdown into HTML using CommonMark:

use Illuminate\Support\Str;

$html = Str::markdown('# Laravel');

// <h1>Laravel</h1>

$html = Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]);

// <h1>Taylor Otwell</h1>

Str::mask() {.collection-method}

The Str::mask method masks a portion of a string with a repeated character, and may be used to obfuscate segments of strings such as email addresses and phone numbers:

use Illuminate\Support\Str;

$string = Str::mask('taylor@example.com', '*', 3);

// tay***************

If needed, you provide a negative number as the third argument to the mask method, which will instruct the method to begin masking at the given distance from the end of the string:

$string = Str::mask('taylor@example.com', '*', -15, 3);

// tay***@example.com

Str::padBoth() {.collection-method}

The Str::padBoth method wraps PHP's str_pad function, padding both sides of a string with another string until the final string reaches a desired length:

use Illuminate\Support\Str;

$padded = Str::padBoth('James', 10, '_');

// '__James___'

$padded = Str::padBoth('James', 10);

// '  James   '

Str::padLeft() {.collection-method}

The Str::padLeft method wraps PHP's str_pad function, padding the left side of a string with another string until the final string reaches a desired length:

use Illuminate\Support\Str;

$padded = Str::padLeft('James', 10, '-=');

// '-=-=-James'

$padded = Str::padLeft('James', 10);

// '     James'

Str::padRight() {.collection-method}

The Str::padRight method wraps PHP's str_pad function, padding the right side of a string with another string until the final string reaches a desired length:

use Illuminate\Support\Str;

$padded = Str::padRight('James', 10, '-');

// 'James-----'

$padded = Str::padRight('James', 10);

// 'James     '

Str::password() {.collection-method}

The Str::password method may be used to generate a secure, random password of a given length. The password will consist of a combination of letters, numbers, symbols, and spaces. By default, passwords are 32 characters long:

use Illuminate\Support\Str;

$password = Str::password();

// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'

$password = Str::password(12);

// 'qwuar>#V|i]N'

Str::plural() {.collection-method}

The Str::plural method converts a singular word string to its plural form. This function supports any of the languages support by Laravel's pluralizer:

use Illuminate\Support\Str;

$plural = Str::plural('car');

// cars

$plural = Str::plural('child');

// children

You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:

use Illuminate\Support\Str;

$plural = Str::plural('child', 2);

// children

$singular = Str::plural('child', 1);

// child

Str::pluralStudly() {.collection-method}

The Str::pluralStudly method converts a singular word string formatted in studly caps case to its plural form. This function supports any of the languages support by Laravel's pluralizer:

use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman');

// VerifiedHumans

$plural = Str::pluralStudly('UserFeedback');

// UserFeedback

You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:

use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman', 2);

// VerifiedHumans

$singular = Str::pluralStudly('VerifiedHuman', 1);

// VerifiedHuman

Str::remove() {.collection-method}

The Str::remove method removes the given value or array of values from the string:

use Illuminate\Support\Str;

$string = 'Peter Piper picked a peck of pickled peppers.';

$removed = Str::remove('e', $string);

// Ptr Pipr pickd a pck of pickld ppprs.

You may also pass false as a third argument to the remove method to ignore case when removing strings.

Str::repeat() {.collection-method}

The Str::repeat method repeats the given string:

use Illuminate\Support\Str;

$string = 'a';

$repeat = Str::repeat($string, 5);

// aaaaa

Str::replace() {.collection-method}

The Str::replace method replaces a given string within the string:

use Illuminate\Support\Str;

$string = 'Laravel 8.x';

$replaced = Str::replace('8.x', '9.x', $string);

// Laravel 9.x

The replace method also accepts a caseSensitive argument. By default, the replace method is case sensitive:

Str::replace('Framework', 'Laravel', caseSensitive: false);

Str::replaceArray() {.collection-method}

The Str::replaceArray method replaces a given value in the string sequentially using an array:

use Illuminate\Support\Str;

$string = 'The event will take place between ? and ?';

$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);

// The event will take place between 8:30 and 9:00

Str::replaceFirst() {.collection-method}

The Str::replaceFirst method replaces the first occurrence of a given value in a string:

use Illuminate\Support\Str;

$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');

// a quick brown fox jumps over the lazy dog

Str::replaceLast() {.collection-method}

The Str::replaceLast method replaces the last occurrence of a given value in a string:

use Illuminate\Support\Str;

$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');

// the quick brown fox jumps over a lazy dog

Str::replaceStart() {.collection-method}

The Str::replaceStart method replaces the first occurrence of the given value only if the value appears at the start of the string:

use Illuminate\Support\Str;

$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');

// Laravel World

$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');

// Hello World

Str::replaceEnd() {.collection-method}

The Str::replaceEnd method replaces the last occurrence of the given value only if the value appears at the end of the string:

use Illuminate\Support\Str;

$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World');

// Hello Laravel

$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World');

// Hello World

Str::reverse() {.collection-method}

The Str::reverse method reverses the given string:

use Illuminate\Support\Str;

$reversed = Str::reverse('Hello World');

// dlroW olleH

Str::singular() {.collection-method}

The Str::singular method converts a string to its singular form. This function supports any of the languages support by Laravel's pluralizer:

use Illuminate\Support\Str;

$singular = Str::singular('cars');

// car

$singular = Str::singular('children');

// child

Str::slug() {.collection-method}

The Str::slug method generates a URL friendly "slug" from the given string:

use Illuminate\Support\Str;

$slug = Str::slug('Laravel 5 Framework', '-');

// laravel-5-framework

Str::snake() {.collection-method}

The Str::snake method converts the given string to snake_case:

use Illuminate\Support\Str;

$converted = Str::snake('fooBar');

// foo_bar

$converted = Str::snake('fooBar', '-');

// foo-bar

Str::squish() {.collection-method}

The Str::squish method removes all extraneous white space from a string, including extraneous white space between words:

use Illuminate\Support\Str;

$string = Str::squish('    laravel    framework    ');

// laravel framework

Str::start() {.collection-method}

The Str::start method adds a single instance of the given value to a string if it does not already start with that value:

use Illuminate\Support\Str;

$adjusted = Str::start('this/string', '/');

// /this/string

$adjusted = Str::start('/this/string', '/');

// /this/string

Str::startsWith() {.collection-method}

The Str::startsWith method determines if the given string begins with the given value:

use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

If an array of possible values is passed, the startsWith method will return true if the string begins with any of the given values:

$result = Str::startsWith('This is my name', ['This', 'That', 'There']);

// true

Str::studly() {.collection-method}

The Str::studly method converts the given string to StudlyCase:

use Illuminate\Support\Str;

$converted = Str::studly('foo_bar');

// FooBar

Str::substr() {.collection-method}

The Str::substr method returns the portion of string specified by the start and length parameters:

use Illuminate\Support\Str;

$converted = Str::substr('The Laravel Framework', 4, 7);

// Laravel

Str::substrCount() {.collection-method}

The Str::substrCount method returns the number of occurrences of a given value in the given string:

use Illuminate\Support\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str::substrReplace() {.collection-method}

The Str::substrReplace method replaces text within a portion of a string, starting at the position specified by the third argument and replacing the number of characters specified by the fourth argument. Passing 0 to the method's fourth argument will insert the string at the specified position without replacing any of the existing characters in the string:

use Illuminate\Support\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str::swap() {.collection-method}

The Str::swap method replaces multiple values in the given string using PHP's strtr function:

use Illuminate\Support\Str;

$string = Str::swap([
    'Tacos' => 'Burritos',
    'great' => 'fantastic',
], 'Tacos are great!');

// Burritos are fantastic!

Str::title() {.collection-method}

The Str::title method converts the given string to Title Case:

use Illuminate\Support\Str;

$converted = Str::title('a nice title uses the correct case');

// A Nice Title Uses The Correct Case

Str::toHtmlString() {.collection-method}

The Str::toHtmlString method converts the string instance to an instance of Illuminate\Support\HtmlString, which may be displayed in Blade templates:

use Illuminate\Support\Str;

$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::ucfirst() {.collection-method}

The Str::ucfirst method returns the given string with the first character capitalized:

use Illuminate\Support\Str;

$string = Str::ucfirst('foo bar');

// Foo bar

Str::ucsplit() {.collection-method}

The Str::ucsplit method splits the given string into an array by uppercase characters:

use Illuminate\Support\Str;

$segments = Str::ucsplit('FooBar');

// [0 => 'Foo', 1 => 'Bar']

Str::upper() {.collection-method}

The Str::upper method converts the given string to uppercase:

use Illuminate\Support\Str;

$string = Str::upper('laravel');

// LARAVEL

Str::ulid() {.collection-method}

The Str::ulid method generates a ULID, which is a compact, time-ordered unique identifier:

use Illuminate\Support\Str;

return (string) Str::ulid();

// 01gd6r360bp37zj17nxb55yv40

If you would like to retrieve a Illuminate\Support\Carbon date instance representing the date and time that a given ULID was created, you may use the createFromId method provided by Laravel's Carbon integration:

use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

$date = Carbon::createFromId((string) Str::ulid());

Str::wordCount() {.collection-method}

The Str::wordCount method returns the number of words that a string contains:

use Illuminate\Support\Str;

Str::wordCount('Hello, world!'); // 2

Str::wordWrap() {.collection-method}

The Str::wordWrap method wraps a string to a given number of characters:

use Illuminate\Support\Str;

$text = "The quick brown fox jumped over the lazy dog."

Str::wordWrap($text, characters: 20, break: "<br />\n");

/*
The quick brown fox<br />
jumped over the lazy<br />
dog.
*/

Str::words() {.collection-method}

The Str::words method limits the number of words in a string. An additional string may be passed to this method via its third argument to specify which string should be appended to the end of the truncated string:

use Illuminate\Support\Str;

return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');

// Perfectly balanced, as >>>

Str::wrap() {.collection-method}

The Str::wrap method wraps the given string with an additional string or pair of strings:

use Illuminate\Support\Str;

Str::wrap('Laravel', '"');

// "Laravel"

Str::wrap('is', before: 'This ', after: ' Laravel!');

// This is Laravel!

str() {.collection-method}

The str function returns a new Illuminate\Support\Stringable instance of the given string. This function is equivalent to the Str::of method:

$string = str('Taylor')->append(' Otwell');

// 'Taylor Otwell'

If no argument is provided to the str function, the function returns an instance of Illuminate\Support\Str:

$snake = str()->snake('FooBar');

// 'foo_bar'

trans() {.collection-method}

The trans function translates the given translation key using your language files:

echo trans('messages.welcome');

If the specified translation key does not exist, the trans function will return the given key. So, using the example above, the trans function would return messages.welcome if the translation key does not exist.

trans_choice() {.collection-method}

The trans_choice function translates the given translation key with inflection:

echo trans_choice('messages.notifications', $unreadCount);

If the specified translation key does not exist, the trans_choice function will return the given key. So, using the example above, the trans_choice function would return messages.notifications if the translation key does not exist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment