Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Laravel Fluent String Methods

  1. after
  2. afterLast
  3. append
  4. ascii
  5. basename
  6. before
  7. beforeLast
  8. between
  9. betweenFirst
  10. camel
  11. classBasename
  12. contains
  13. containsAll
  14. dirname
  15. endsWith
  16. excerpt
  17. exactly
  18. explode
  19. finish
  20. inlineMarkdown
  21. is
  22. isAscii
  23. isEmpty
  24. isNotEmpty
  25. isJson
  26. isUuid
  27. kebab
  28. lcfirst
  29. length
  30. limit
  31. lower
  32. ltrim
  33. markdown
  34. mask
  35. match
  36. matchAll
  37. newLine
  38. padBoth
  39. padLeft
  40. padRight
  41. pipe
  42. plural
  43. prepend
  44. remove
  45. replace
  46. replaceArray
  47. replaceFirst
  48. replaceLast
  49. replaceMatches
  50. rtrim
  51. scan
  52. singular
  53. slug
  54. snake
  55. split
  56. squish
  57. start
  58. startsWith
  59. studly
  60. substr
  61. substrReplace
  62. swap
  63. tap
  64. test
  65. title
  66. trim
  67. ucfirst
  68. ucsplit
  69. upper
  70. when
  71. whenContains
  72. whenContainsAll
  73. whenEmpty
  74. whenNotEmpty
  75. whenStartsWith
  76. whenEndsWith
  77. whenExactly
  78. whenNotExactly
  79. whenIs
  80. whenIsAscii
  81. whenIsUuid
  82. whenTest
  83. wordCount
  84. words

Important used Array Methods

  1. after(returns everything after the given value in a string)
  2. append(appends the given values to the string:)
  3. ascii(attempt to transliterate the string into an ASCII value)
  4. before(eturns everything before the given value in a string)
  5. camel(converts the given string to camelCase)
  6. contains,containsAll(etermines if the given string contains the given value
  7. containsAll(determines if the given string contains all of the values in the given array)
  8. endsWith(determines if the given string ends with the given value)
  9. exactly(determines if the given string is an exact match with another string)
  10. explode(splits the string by the given delimiter and returns a collection containing each section of the split string)
  11. is(if a given string matches a given pattern)
  12. isEmpty(if the given string is empty)
  13. isNotEmpty(if the given string is not empty)
  14. isUuid(if a given string is a UUID)
  15. length(returns the length of the given string)
  16. limit(given string to the specified length)
  17. match(return the portion of a string that matches a given regular expression pattern)
  18. matchAll(return a collection containing the portions of a string that match a given regular expression pattern)
  19. newLine(appends an "end of line" character to a string)
  20. padBoth(padding both sides of a string with another string until the final string reaches the desired length)
  21. prepend(prepends the given values onto the string:)
  22. remove(removes the given value or array of values from the string)
  23. replace(replaces a given string within the string)
  24. slug(generates a URL friendly "slug" from the given string:)
  25. split(splits a string into a collection using a regular expression)
  26. substr( returns the portion of the string specified by the given start and length parameters:)
  27. substrReplace(replaces text within a portion of a string, starting at the position specified by the second argument and replacing the number of characters specified by the third argument.)
  28. swap(eplaces multiple values in the string using PHP's strtr function)
  29. whenContains(invokes the given closure if the string contains the given value)
  30. whenContainsAll(invokes the given closure if the string contains all of the given sub-strings.)
  31. whenEmpty( invokes the given closure if the string is empty)
  32. whenNotEmpty(invokes the given closure if the string is not empty. If the closure returns a value, that value will also be returned by the whenNotEmpty method)
  33. whenStartsWith(invokes the given closure if the string starts with the given sub-string)
  34. wordCount( returns the number of words that a string contains)

after
The 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::of('This is my name')->after('This is');

// ' my name'
Enter fullscreen mode Exit fullscreen mode

afterLast
The 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::of('App\Http\Controllers\Controller')->afterLast('\\');

// 'Controller'
Enter fullscreen mode Exit fullscreen mode

append
The append method appends the given values to the string:

use Illuminate\Support\Str;

$string = Str::of('Taylor')->append(' Otwell');

// 'Taylor Otwell'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$string = Str::of('ü')->ascii();

// 'u'
Enter fullscreen mode Exit fullscreen mode

basename
The basename method will return the trailing name component of the given string:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->basename();

// 'baz'
Enter fullscreen mode Exit fullscreen mode

If needed, you may provide an "extension" that will be removed from the trailing component:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');

// 'baz'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->before('my name');

// 'This is '
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->beforeLast('is');

// 'This '

between
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$converted = Str::of('This is my name')->between('This', 'name');

// ' is my '

betweenFirst
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');

// 'a'
Enter fullscreen mode Exit fullscreen mode

camel
The camel method converts the given string to camelCase:

use Illuminate\Support\Str;

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

// fooBar
Enter fullscreen mode Exit fullscreen mode

classBasename
The classBasename method returns the class name of the given class with the class's namespace removed:

use Illuminate\Support\Str;

$class = Str::of('Foo\Bar\Baz')->classBasename();

// Baz
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$contains = Str::of('This is my name')->contains('my');

// true
Enter fullscreen mode Exit fullscreen mode

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::of('This is my name')->contains(['my', 'foo']);

// true
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// true
Enter fullscreen mode Exit fullscreen mode

dirname
The dirname method returns the parent directory portion of the given string:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname();

// '/foo/bar'
Enter fullscreen mode Exit fullscreen mode

If necessary, you may specify how many directory levels you wish to trim from the string:

use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname(2);

// '/foo'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// '...is my na...'
Enter fullscreen mode Exit fullscreen mode

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 change the string that will be prepended and appended to the truncated string:

use Illuminate\Support\Str;

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

// '(...) my name'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$result = Str::of('This is my name')->endsWith('name');

// true
Enter fullscreen mode Exit fullscreen mode

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::of('This is my name')->endsWith(['name', 'foo']);

// true

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

// false
Enter fullscreen mode Exit fullscreen mode

exactly
The exactly method determines if the given string is an exact match with another string:

use Illuminate\Support\Str;

$result = Str::of('Laravel')->exactly('Laravel');

// true
Enter fullscreen mode Exit fullscreen mode

explode
The explode method splits the string by the given delimiter and returns a collection containing each section of the split string:

use Illuminate\Support\Str;

$collection = Str::of('foo bar baz')->explode(' ');

// collect(['foo', 'bar', 'baz'])
Enter fullscreen mode Exit fullscreen mode

finish
The 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::of('this/string')->finish('/');

// this/string/

$adjusted = Str::of('this/string/')->finish('/');

// this/string/

inlineMarkdown
Enter fullscreen mode Exit fullscreen mode

The 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::of('**Laravel**')->inlineMarkdown();

// <strong>Laravel</strong>
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$matches = Str::of('foobar')->is('foo*');

// true

$matches = Str::of('foobar')->is('baz*');

// false

isAscii
Enter fullscreen mode Exit fullscreen mode

The isAscii method determines if a given string is an ASCII string:

use Illuminate\Support\Str;

$result = Str::of('Taylor')->isAscii();

// true

$result = Str::of('ü')->isAscii();

// false

isEmpty
The isEmpty method determines if the given string is empty:

use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isEmpty();

// true

$result = Str::of('Laravel')->trim()->isEmpty();

// false
Enter fullscreen mode Exit fullscreen mode

isNotEmpty
The isNotEmpty method determines if the given string is not empty:

use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isNotEmpty();

// false

$result = Str::of('Laravel')->trim()->isNotEmpty();

// true
Enter fullscreen mode Exit fullscreen mode

isJson
The isJson method determines if a given string is valid JSON:

use Illuminate\Support\Str;

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

// true

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

// true

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

// false
Enter fullscreen mode Exit fullscreen mode

isUuid
The isUuid method determines if a given string is a UUID:

use Illuminate\Support\Str;

$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();

// true

$result = Str::of('Taylor')->isUuid();

// false

kebab
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// foo-bar
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// foo Bar
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$length = Str::of('Laravel')->length();

// 7
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
Enter fullscreen mode Exit fullscreen mode

// The quick brown fox...

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

use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
Enter fullscreen mode Exit fullscreen mode

// The quick brown fox (...)

lower
The lower method converts the given string to lowercase:

use Illuminate\Support\Str;

$result = Str::of('LARAVEL')->lower();

// 'laravel'
Enter fullscreen mode Exit fullscreen mode

ltrim
The ltrim method trims the left side of the string:

use Illuminate\Support\Str;

$string = Str::of('  Laravel  ')->ltrim();

// 'Laravel  '

$string = Str::of('/Laravel/')->ltrim('/');

// 'Laravel/'
Enter fullscreen mode Exit fullscreen mode

markdown
The markdown method converts GitHub flavored Markdown into HTML:

use Illuminate\Support\Str;

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

// <h1>Laravel</h1>

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

// <h1>Taylor Otwell</h1>
Enter fullscreen mode Exit fullscreen mode

mask
The 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::of('taylor@example.com')->mask('*', 3);

// tay***************
Enter fullscreen mode Exit fullscreen mode

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::of('taylor@example.com')->mask('*', -15, 3);

// tay***@example.com
Enter fullscreen mode Exit fullscreen mode

match
The match method will return the portion of a string that matches a given regular expression pattern:

use Illuminate\Support\Str;

$result = Str::of('foo bar')->match('/bar/');

// 'bar'

$result = Str::of('foo bar')->match('/foo (.*)/');

// 'bar'
Enter fullscreen mode Exit fullscreen mode

matchAll
The matchAll method will return a collection containing the portions of a string that match a given regular expression pattern:

use Illuminate\Support\Str;

$result = Str::of('bar foo bar')->matchAll('/bar/');

// collect(['bar', 'bar'])
Enter fullscreen mode Exit fullscreen mode

If you specify a matching group within the expression, Laravel will return a collection of that group's matches:

use Illuminate\Support\Str;

$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');

// collect(['un', 'ly']);
Enter fullscreen mode Exit fullscreen mode

If no matches are found, an empty collection will be returned.

newLine
The newLine method appends an "end of line" character to a string:

use Illuminate\Support\Str;

$padded = Str::of('Laravel')->newLine()->append('Framework');

// 'Laravel
//  Framework'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// '__James___'

$padded = Str::of('James')->padBoth(10);

// '  James   
Enter fullscreen mode Exit fullscreen mode

'

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

use Illuminate\Support\Str;

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

// '-=-=-James'

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

// '     James'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James  
Enter fullscreen mode Exit fullscreen mode

'

pipe
The pipe method allows you to transform the string by passing its current value to the given callable:

use Illuminate\Support\Str;

$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');

// 'Checksum: a5c95b86291ea299fcbe64458ed12702'

$closure = Str::of('foo')->pipe(function ($str) {
    return 'bar';
});

// 'bar'
Enter fullscreen mode Exit fullscreen mode

plural
The 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::of('car')->plural();

// cars

$plural = Str::of('child')->plural();

// children
Enter fullscreen mode Exit fullscreen mode

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::of('child')->plural(2);

// children

$plural = Str::of('child')->plural(1);

// child
Enter fullscreen mode Exit fullscreen mode

prepend
The prepend method prepends the given values onto the string:

use Illuminate\Support\Str;

$string = Str::of('Framework')->prepend('Laravel ');

// Laravel Framework
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$string = Str::of('Arkansas is quite beautiful!')->remove('quite');

// Arkansas is beautiful!
Enter fullscreen mode Exit fullscreen mode

You may also pass false as a second parameter to ignore case when removing strings.

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

use Illuminate\Support\Str;

$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');

// Laravel 7.x
Enter fullscreen mode Exit fullscreen mode

replaceArray
The 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::of($string)->replaceArray('?', ['8:30', '9:00']);

// The event will take place between 8:30 and 9:00
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// a quick brown fox jumps over the lazy dog
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// the quick brown fox jumps over a lazy dog
Enter fullscreen mode Exit fullscreen mode

replaceMatches
The replaceMatches method replaces all portions of a string matching a pattern with the given replacement string:

use Illuminate\Support\Str;

$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')

// '15015551000'
Enter fullscreen mode Exit fullscreen mode

The replaceMatches method also accepts a closure that will be invoked with each portion of the string matching the given pattern, allowing you to perform the replacement logic within the closure and return the replaced value:

use Illuminate\Support\Str;

$replaced = Str::of('123')->replaceMatches('/\d/', function ($match) {
    return '['.$match[0].']';
});

// '[1][2][3]'
Enter fullscreen mode Exit fullscreen mode

rtrim
The rtrim method trims the right side of the given string:

use Illuminate\Support\Str;

$string = Str::of('  Laravel  ')->rtrim();

// '  Laravel'

$string = Str::of('/Laravel/')->rtrim('/');

// '/Laravel'
Enter fullscreen mode Exit fullscreen mode

scan
The scan method parses input from a string into a collection according to a format supported by the sscanf PHP function:

use Illuminate\Support\Str;

$collection = Str::of('filename.jpg')->scan('%[^.].%s');

// collect(['filename', 'jpg'])
Enter fullscreen mode Exit fullscreen mode

singular
The 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::of('cars')->singular();

// car

$singular = Str::of('children')->singular();

// child
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$slug = Str::of('Laravel Framework')->slug('-');

// laravel-framework
Enter fullscreen mode Exit fullscreen mode

snake
The snake method converts the given string to snake_case:

use Illuminate\Support\Str;

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

// foo_bar
Enter fullscreen mode Exit fullscreen mode

split
The split method splits a string into a collection using a regular expression:

use Illuminate\Support\Str;

$segments = Str::of('one, two, three')->split('/[\s,]+/');

// collect(["one", "two", "three"])
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// laravel framework
Enter fullscreen mode Exit fullscreen mode

start
The 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::of('this/string')->start('/');

// /this/string

$adjusted = Str::of('/this/string')->start('/');

// /this/string
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$result = Str::of('This is my name')->startsWith('This');

// true
Enter fullscreen mode Exit fullscreen mode

studly
The studly method converts the given string to StudlyCase:

use Illuminate\Support\Str;

$converted = Str::of('foo_bar')->studly();

// FooBar
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$string = Str::of('Laravel Framework')->substr(8);

// Framework

$string = Str::of('Laravel Framework')->substr(8, 5);

// Frame
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$string = Str::of('1300')->substrReplace(':', 2);

// 13:

$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);

// The Laravel Framework
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// Burritos are fantastic!
Enter fullscreen mode Exit fullscreen mode

tap
The tap method passes the string to the given closure, allowing you to examine and interact with the string while not affecting the string itself. The original string is returned by the tap method regardless of what is returned by the closure:

use Illuminate\Support\Str;

$string = Str::of('Laravel')
    ->append(' Framework')
    ->tap(function ($string) {
        dump('String after append: '.$string);
    })
    ->upper();

// LARAVEL FRAMEWORK


Enter fullscreen mode Exit fullscreen mode

test
The test method determines if a string matches the given regular expression pattern:

use Illuminate\Support\Str;

$result = Str::of('Laravel Framework')->test('/Laravel/');

// true
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

$converted = Str::of('a nice title uses the correct case')->title();
Enter fullscreen mode Exit fullscreen mode

// A Nice Title Uses The Correct Case

trim
The trim method trims the given string:

use Illuminate\Support\Str;

$string = Str::of('  Laravel  ')->trim();

// 'Laravel'

$string = Str::of('/Laravel/')->trim('/');

// 'Laravel'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

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

// Foo bar
Enter fullscreen mode Exit fullscreen mode

ucsplit
The ucsplit method splits the given string into a collection by uppercase characters:

use Illuminate\Support\Str;

$string = Str::of('Foo Bar')->ucsplit();

// collect(['Foo', 'Bar'])
Enter fullscreen mode Exit fullscreen mode

upper
The upper method converts the given string to uppercase:

use Illuminate\Support\Str;

$adjusted = Str::of('laravel')->upper();

// LARAVEL
Enter fullscreen mode Exit fullscreen mode

when
The when method invokes the given closure if a given condition is true. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('Taylor')
                ->when(true, function ($string) {
                    return $string->append(' Otwell');
                });

// 'Taylor Otwell'
Enter fullscreen mode Exit fullscreen mode

If necessary, you may pass another closure as the third parameter to the when method. This closure will execute if the condition parameter evaluates to false.

whenContains
The whenContains method invokes the given closure if the string contains the given value. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('tony stark')
            ->whenContains('tony', function ($string) {
                return $string->title();
            });
Enter fullscreen mode Exit fullscreen mode

// 'Tony Stark'

If necessary, you may pass another closure as the third parameter to the when method. This closure will execute if the string does not contain the given value.

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;

$string = Str::of('tony stark')
            ->whenContains(['tony', 'hulk'], function ($string) {
                return $string->title();
            });

// Tony Stark
Enter fullscreen mode Exit fullscreen mode

whenContainsAll
The whenContainsAll method invokes the given closure if the string contains all of the given sub-strings. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('tony stark')
                ->whenContainsAll(['tony', 'stark'], function ($string) {
                    return $string->title();
                });

// 'Tony Stark'
Enter fullscreen mode Exit fullscreen mode

If necessary, you may pass another closure as the third parameter to the when method. This closure will execute if the condition parameter evaluates to false.

whenEmpty
The whenEmpty method invokes the given closure if the string is empty. If the closure returns a value, that value will also be returned by the whenEmpty method. If the closure does not return a value, the fluent string instance will be returned:

use Illuminate\Support\Str;

$string = Str::of('  ')->whenEmpty(function ($string) {
    return $string->trim()->prepend('Laravel');
});

// 'Laravel'
Enter fullscreen mode Exit fullscreen mode

whenNotEmpty
The whenNotEmpty method invokes the given closure if the string is not empty. If the closure returns a value, that value will also be returned by the whenNotEmpty method. If the closure does not return a value, the fluent string instance will be returned:

use Illuminate\Support\Str;

$string = Str::of('Framework')->whenNotEmpty(function ($string) {
    return $string->prepend('Laravel ');
});

// 'Laravel Framework'
Enter fullscreen mode Exit fullscreen mode

whenStartsWith
The whenStartsWith method invokes the given closure if the string starts with the given sub-string. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('disney world')->whenStartsWith('disney', function ($string) {
    return $string->title();
});

// 'Disney World'
Enter fullscreen mode Exit fullscreen mode

whenEndsWith
The whenEndsWith method invokes the given closure if the string ends with the given sub-string. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('disney world')->whenEndsWith('world', function ($string) {
    return $string->title();
});

// 'Disney World'
Enter fullscreen mode Exit fullscreen mode

whenExactly
The whenExactly method invokes the given closure if the string exactly matches the given string. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('laravel')->whenExactly('laravel', function ($string) {
    return $string->title();
});

// 'Laravel'
Enter fullscreen mode Exit fullscreen mode

whenNotExactly
The whenNotExactly method invokes the given closure if the string does not exactly match the given string. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('framework')->whenNotExactly('laravel', function ($string) {
    return $string->title();
});

// 'Framework'
Enter fullscreen mode Exit fullscreen mode

whenIs
The whenIs method invokes the given closure if the string matches a given pattern. Asterisks may be used as wildcard values. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('foo/bar')->whenIs('foo/*', function ($string) {
    return $string->append('/baz');
});

// 'foo/bar/baz'
Enter fullscreen mode Exit fullscreen mode

whenIsAscii
The whenIsAscii method invokes the given closure if the string is 7 bit ASCII. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('foo/bar')->whenIsAscii('laravel', function ($string) {
    return $string->title();
});

// 'Laravel'
Enter fullscreen mode Exit fullscreen mode

whenIsUuid
The whenIsUuid method invokes the given closure if the string is a valid UUID. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('foo/bar')->whenIsUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', function ($string) {
    return $string->substr(0, 8);
});

// 'a0a2a2d2'
Enter fullscreen mode Exit fullscreen mode

whenTest
The whenTest method invokes the given closure if the string matches the given regular expression. The closure will receive the fluent string instance:

use Illuminate\Support\Str;

$string = Str::of('laravel framework')->whenTest('/laravel/', function ($string) {
    return $string->title();
});

// 'Laravel Framework'
Enter fullscreen mode Exit fullscreen mode

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

use Illuminate\Support\Str;

Str::of('Hello, world!')->wordCount(); // 2
Enter fullscreen mode Exit fullscreen mode

words
The words method limits the number of words in a string. If necessary, you may specify an additional string that will be appended to the truncated string:

use Illuminate\Support\Str;

$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');

// Perfectly balanced, as >>>
Enter fullscreen mode Exit fullscreen mode

In Laravel-9 new String Method

Laravel 9 comes with several new helper functions that make development easier and more efficient. Here are some examples of new helper functions in Laravel 9 and how to use them:

assertIsIterable($value): This helper function asserts that a given value is an iterable type. If the assertion fails, it will throw an InvalidArgumentException with a useful message.

$array = [1, 2, 3];
assertIsIterable($array); // Assertion passes

$int = 42;
assertIsIterable($int); // Assertion fails with "Expected iterable, got integer" error message
Enter fullscreen mode Exit fullscreen mode

blank($value): This helper function determines whether a given value is "blank". A value is considered blank if it is null, an empty string, or an empty array.

$value = '';
if (blank($value)) {
    echo 'The value is blank';
} else {
    echo 'The value is not blank';
}
Enter fullscreen mode Exit fullscreen mode

filled($value): This helper function is the opposite of blank(). It determines whether a given value is "filled", meaning it is not null, not an empty string, and not an empty array.

$value = 'foo';
if (filled($value)) {
    echo 'The value is filled';
} else {
    echo 'The value is not filled';
}
Enter fullscreen mode Exit fullscreen mode

once($callback): This helper function ensures that a given callback is only executed once. The first time the callback is executed, the result is cached and returned on subsequent calls.

$callback = function () {
    echo 'This is executed only once';
};

once($callback); // Output: "This is executed only once"
once($callback); // No output, since the result is cached from the previous call
Enter fullscreen mode Exit fullscreen mode

These are just a few examples of the new helper functions in Laravel 9. For a full list of helper functions and their usage, you can refer to the official Laravel documentation.

Laravel 9 introduces several new helper functions for strings that make working with strings more convenient. Here are some examples of new helper functions for strings in Laravel 9 and how to use them:

starts_with($haystack, $needles): This helper function determines whether a given string starts with one or more specified substrings.

$string = 'Hello world';
if (starts_with($string, 'Hello')) {
    echo 'The string starts with "Hello"';
}
Enter fullscreen mode Exit fullscreen mode

ends_with($haystack, $needles): This helper function determines whether a given string ends with one or more specified substrings.

$string = 'Hello world';
if (ends_with($string, 'world')) {
    echo 'The string ends with "world"';
}
Enter fullscreen mode Exit fullscreen mode

str_contains($haystack, $needle): This helper function determines whether a given string contains a specified substring.

$string = 'Hello world';
if (str_contains($string, 'world')) {
    echo 'The string contains "world"';
}
Enter fullscreen mode Exit fullscreen mode

str_plural($value, $count = 2): This helper function returns the plural form of a given word, based on the specified count.

$word = 'apple';
$count = 3;
$plural = str_plural($word, $count); // Output: "apples"
Enter fullscreen mode Exit fullscreen mode

str_singular($value): This helper function returns the singular form of a given word.

$word = 'apples';
$singular = str_singular($word); // Output: "apple"
Enter fullscreen mode Exit fullscreen mode

Laravel 9 comes with several new helper functions for strings that make working with strings more convenient. Here is a list of all new helper functions for strings in Laravel 9 and their examples:

ascii($value): This helper function converts a string to ASCII.

$string = 'Héllo';
$ascii = ascii($string); // Output: "Hello"
camel_case($value): This helper function converts a string to camel case.
Enter fullscreen mode Exit fullscreen mode
$string = 'hello_world';
$camelCase = camel_case($string); // Output: "helloWorld"
kebab_case($value): This helper function converts a string to kebab case.
Enter fullscreen mode Exit fullscreen mode
$string = 'HelloWorld';
$kebabCase = kebab_case($string); // Output: "hello-world"
snake_case($value): This helper function converts a string to snake case.
Enter fullscreen mode Exit fullscreen mode
$string = 'HelloWorld';
$snakeCase = snake_case($string); // Output: "hello_world"
start($value, $prefix): This helper function adds a prefix to a string, if it doesn't already have it.

$string = 'world';
$prefix = 'Hello ';
$result = start($string, $prefix); // Output: "Hello world"
Enter fullscreen mode Exit fullscreen mode

starts_with($haystack, $needles): This helper function determines whether a given string starts with one or more specified substrings.

$string = 'Hello world';
if (starts_with($string, 'Hello')) {
    echo 'The string starts with "Hello"';
}
Enter fullscreen mode Exit fullscreen mode

ends_with($haystack, $needles): This helper function determines whether a given string ends with one or more specified substrings.

$string = 'Hello world';
if (ends_with($string, 'world')) {
    echo 'The string ends with "world"';
}
Enter fullscreen mode Exit fullscreen mode

str_after($subject, $search): This helper function returns the part of a string that comes after a specified search string.

$string = 'Hello world';
$after = str_after($string, 'Hello '); // Output: "world"
Enter fullscreen mode Exit fullscreen mode

str_before($subject, $search): This helper function returns the part of a string that comes before a specified search string.

$string = 'Hello world';
$before = str_before($string, ' world'); // Output: "Hello"
Enter fullscreen mode Exit fullscreen mode

str_contains($haystack, $needle): This helper function determines whether a given string contains a specified substring.

$string = 'Hello world';
if (str_contains($string, 'world')) {
    echo 'The string contains "world"';
}
Enter fullscreen mode Exit fullscreen mode

str_finish($value, $cap): This helper function adds a suffix to a string, if it doesn't already have it.

$string = 'Hello';
$suffix = '!';
$result = str_finish($string, $suffix); // Output: "Hello!"
Enter fullscreen mode Exit fullscreen mode

str_is($pattern, $value): This helper function determines whether a given string matches a specified pattern.

$string = 'Hello world';
if (str_is('Hello*', $string)) {
    echo 'The string starts with "Hello"';
}
Enter fullscreen mode Exit fullscreen mode

str_plural($value, $count = 2): This helper function returns the plural form of a given word, based on the specified count.

$word = 'apple';
$count = 3;
$plural = str_plural($word, $count); // Output: "apples
Enter fullscreen mode Exit fullscreen mode

Here's an example of how to use Str::of helper function:

use Illuminate\Support\Str;

$string = 'Laravel is awesome';

// Make the string lowercase and capitalize the first letter
$result = Str::of($string)->lower()->ucfirst();

echo $result; // Output: "Laravel is awesome"
Enter fullscreen mode Exit fullscreen mode

In the above example, we first import the Illuminate\Support\Str class and then create a new instance of the class using the Str::of method, passing in the string we want to work with.

We then chain two methods, lower and ucfirst, to make the string lowercase and capitalize the first letter. Finally, we output the modified string.

The Str::of method provides a more expressive and readable way of working with strings, and it can be used to chain multiple string operations together.
In Laravel 9, the Str::of helper function can be used with the append method to concatenate additional strings to the original string.

Here's an example of how to use Str::of helper function with append method:

use Illuminate\Support\Str;

$string = 'Laravel is awesome';

// Append two more strings to the original string
$result = Str::of($string)->append(', and it gets better', ' every day!');

echo $result; // Output: "Laravel is awesome, and it gets better every day!"
Enter fullscreen mode Exit fullscreen mode

In the above example, we first import the Illuminate\Support\Str class and then create a new instance of the class using the Str::of method, passing in the string we want to work with.

We then call the append method on the instance, passing in two additional strings we want to concatenate to the original string. The append method can take any number of arguments, and each argument will be concatenated to the end of the original string in the order they are provided.

Finally, we output the modified string.

The Str::of method with append provides a convenient way of concatenating strings and can be used with other string manipulation methods to create complex string operations.

Top comments (0)