- after
- afterLast
- append
- ascii
- basename
- before
- beforeLast
- between
- betweenFirst
- camel
- classBasename
- contains
- containsAll
- dirname
- endsWith
- excerpt
- exactly
- explode
- finish
- inlineMarkdown
- is
- isAscii
- isEmpty
- isNotEmpty
- isJson
- isUuid
- kebab
- lcfirst
- length
- limit
- lower
- ltrim
- markdown
- mask
- match
- matchAll
- newLine
- padBoth
- padLeft
- padRight
- pipe
- plural
- prepend
- remove
- replace
- replaceArray
- replaceFirst
- replaceLast
- replaceMatches
- rtrim
- scan
- singular
- slug
- snake
- split
- squish
- start
- startsWith
- studly
- substr
- substrReplace
- swap
- tap
- test
- title
- trim
- ucfirst
- ucsplit
- upper
- when
- whenContains
- whenContainsAll
- whenEmpty
- whenNotEmpty
- whenStartsWith
- whenEndsWith
- whenExactly
- whenNotExactly
- whenIs
- whenIsAscii
- whenIsUuid
- whenTest
- wordCount
- words
Important used Array Methods
- after(returns everything after the given value in a string)
- append(appends the given values to the string:)
- ascii(attempt to transliterate the string into an ASCII value)
- before(eturns everything before the given value in a string)
- camel(converts the given string to camelCase)
- contains,containsAll(etermines if the given string contains the given value
- containsAll(determines if the given string contains all of the values in the given array)
- endsWith(determines if the given string ends with the given value)
- exactly(determines if the given string is an exact match with another string)
- explode(splits the string by the given delimiter and returns a collection containing each section of the split string)
- is(if a given string matches a given pattern)
- isEmpty(if the given string is empty)
- isNotEmpty(if the given string is not empty)
- isUuid(if a given string is a UUID)
- length(returns the length of the given string)
- limit(given string to the specified length)
- match(return the portion of a string that matches a given regular expression pattern)
- matchAll(return a collection containing the portions of a string that match a given regular expression pattern)
- newLine(appends an "end of line" character to a string)
- padBoth(padding both sides of a string with another string until the final string reaches the desired length)
- prepend(prepends the given values onto the string:)
- remove(removes the given value or array of values from the string)
- replace(replaces a given string within the string)
- slug(generates a URL friendly "slug" from the given string:)
- split(splits a string into a collection using a regular expression)
- substr( returns the portion of the string specified by the given start and length parameters:)
- 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.)
- swap(eplaces multiple values in the string using PHP's strtr function)
- whenContains(invokes the given closure if the string contains the given value)
- whenContainsAll(invokes the given closure if the string contains all of the given sub-strings.)
- whenEmpty( invokes the given closure if the string is empty)
- 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)
- whenStartsWith(invokes the given closure if the string starts with the given sub-string)
- 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'
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'
append
The append method appends the given values to the string:
use Illuminate\Support\Str;
$string = Str::of('Taylor')->append(' Otwell');
// 'Taylor Otwell'
ascii
The ascii method will attempt to transliterate the string into an ASCII value:
use Illuminate\Support\Str;
$string = Str::of('ü')->ascii();
// 'u'
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'
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'
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 '
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
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
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'
camel
The camel method converts the given string to camelCase:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->camel();
// fooBar
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
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
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
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
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'
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'
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...'
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'
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
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
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
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'])
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
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>
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
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
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
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
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
The kebab method converts the given string to kebab-case:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->kebab();
// foo-bar
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
length
The length method returns the length of the given string:
use Illuminate\Support\Str;
$length = Str::of('Laravel')->length();
// 7
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);
// 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, ' (...)');
// The quick brown fox (...)
lower
The lower method converts the given string to lowercase:
use Illuminate\Support\Str;
$result = Str::of('LARAVEL')->lower();
// 'laravel'
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/'
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>
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***************
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
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'
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'])
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']);
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'
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
'
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'
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
'
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'
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
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
prepend
The prepend method prepends the given values onto the string:
use Illuminate\Support\Str;
$string = Str::of('Framework')->prepend('Laravel ');
// Laravel Framework
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!
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
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
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
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
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'
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]'
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'
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'])
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
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
snake
The snake method converts the given string to snake_case:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->snake();
// foo_bar
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"])
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
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
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
studly
The studly method converts the given string to StudlyCase:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->studly();
// FooBar
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
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
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!
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
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
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();
// 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'
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
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'])
upper
The upper method converts the given string to uppercase:
use Illuminate\Support\Str;
$adjusted = Str::of('laravel')->upper();
// LARAVEL
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'
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();
});
// '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
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'
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'
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'
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'
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'
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'
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'
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'
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'
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'
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'
wordCount
The wordCount method returns the number of words that a string contains:
use Illuminate\Support\Str;
Str::of('Hello, world!')->wordCount(); // 2
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 >>>
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
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';
}
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';
}
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
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"';
}
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"';
}
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"';
}
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"
str_singular($value): This helper function returns the singular form of a given word.
$word = 'apples';
$singular = str_singular($word); // Output: "apple"
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.
$string = 'hello_world';
$camelCase = camel_case($string); // Output: "helloWorld"
kebab_case($value): This helper function converts a string to kebab case.
$string = 'HelloWorld';
$kebabCase = kebab_case($string); // Output: "hello-world"
snake_case($value): This helper function converts a string to snake case.
$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"
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"';
}
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"';
}
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"
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"
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"';
}
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!"
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"';
}
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
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"
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!"
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)