문자열
업데이트됨번역일: 2026년 9월 17일
이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.
- 원문 수정
- 2026년 9월 17일
- 번역 갱신
- 2026년 9월 17일
문자열
소개
라라벨은 문자열 값을 다룰 때 사용할 수 있는 다양한 함수를 기본으로 제공합니다. 이 함수들 중 상당수는 프레임워크 내부에서도 사용되지만, 여러분이 작성하는 애플리케이션 코드에서도 편리하게 활용할 수 있습니다.
사용 가능한 메서드
NOTE
아래 목록에 나온 이름을 클릭하면 해당 메서드에 대한 자세한 설명을 확인할 수 있습니다.
Str::after Str::afterLast Str::apa Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::charAt Str::chopStart Str::chopEnd Str::contains Str::containsAll Str::doesntContain Str::deduplicate Str::endsWith Str::excerpt Str::finish Str::fromBase64 Str::headline Str::inlineMarkdown Str::is Str::isAscii Str::isJson Str::isUrl Str::isUlid Str::isUuid Str::kebab Str::lcfirst Str::length Str::limit Str::lower Str::markdown Str::mask Str::match Str::matchAll Str::numbers Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::password Str::plural Str::pluralPascal Str::pluralStudly Str::position Str::random Str::remove Str::repeat Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::replaceMatches Str::replaceStart Str::replaceEnd Str::reverse Str::singular Str::slug Str::snake Str::squish Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::take Str::title Str::toBase64 Str::toHtmlString Str::transliterate Str::trim Str::ltrim Str::rtrim Str::ucfirst Str::ucsplit Str::upper Str::ulid Str::unwrap Str::uuid Str::uuid7 Str::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
다음 5개 섹션에서는 Str 클래스가 제공하는 각 메서드와 Stringable 유창한(fluent) 문자열 객체의 사용법을 실제 예제와 함께 자세히 살펴보겠습니다. 이어지는 섹션에서 계속됩니다.
문자열
사용 가능한 메서드
문자열
Str::after Str::afterLast Str::apa Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::charAt Str::chopStart Str::chopEnd Str::contains Str::containsAll Str::doesntContain Str::deduplicate Str::endsWith Str::excerpt Str::finish Str::freezeUuids Str::fromBase64 Str::headline Str::inlineMarkdown Str::is Str::isAscii Str::isJson Str::isUlid Str::isUrl Str::isUuid Str::kebab Str::lcfirst Str::length Str::limit Str::lower Str::markdown Str::mask Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::password Str::plural Str::pluralStudly Str::position Str::random Str::remove Str::repeat Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::replaceMatches Str::replaceStart Str::replaceEnd Str::reverse Str::singular Str::slug Str::snake Str::squish Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::take Str::title Str::toBase64 Str::transliterate Str::trim Str::ltrim Str::rtrim Str::ucfirst Str::ucsplit Str::upper Str::ulid Str::unwrap Str::uuid Str::uuid7 Str::wcfirst Str::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
유창한 문자열 (Fluent Strings)
after afterLast apa append ascii basename before beforeLast between betweenFirst camel charAt chopStart chopEnd classBasename contains containsAll decrypt deduplicate dirname doesntContain doesntEndWith doesntStartWith encrypt endsWith exactly excerpt explode finish fromBase64 hash headline inlineMarkdown is isAscii isEmpty isNotEmpty isJson isUlid isUrl isUuid kebab lcfirst length limit lower markdown mask match matchAll isMatch newLine padBoth padLeft padRight pipe plural position prepend remove repeat replace replaceArray replaceFirst replaceLast replaceMatches replaceStart replaceEnd scan singular slug snake split squish start startsWith stripTags studly substr substrReplace swap take tap test title toBase64 toHtmlString toUri transliterate trim ltrim rtrim ucfirst ucsplit unwrap upper when whenContains whenContainsAll whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenDoesntStartWith whenDoesntEndWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words wrap
NOTE
이 목록은 다음 섹션에서 이어지는 "문자열 헬퍼 함수"와 "유창한 문자열" 부분의 목차입니다. 각 메서드의 상세 설명과 예제는 다음 섹션에서 계속됩니다.
문자열
사용 가능한 메서드
문자열 (Strings)
__ class_basename e preg_replace_array Str::after Str::afterLast Str::apa Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::charAt Str::chopStart Str::chopEnd Str::contains Str::containsAll Str::counted Str::doesntContain Str::doesntEndWith Str::doesntStartWith Str::deduplicate Str::endsWith Str::excerpt Str::finish Str::fromBase64 Str::headline Str::initials Str::inlineMarkdown Str::is Str::isAscii Str::isJson Str::isUlid Str::isUrl Str::isUuid Str::kebab Str::lcfirst Str::length Str::limit Str::lower Str::markdown Str::mask Str::match Str::matchAll Str::isMatch Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::password Str::plural Str::pluralStudly Str::position Str::random Str::remove Str::repeat Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::replaceMatches Str::replaceStart Str::replaceEnd Str::reverse Str::singular Str::slug Str::snake Str::squish Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::take Str::title Str::toBase64 Str::transliterate Str::trim Str::ltrim Str::rtrim Str::ucfirst Str::ucsplit Str::ucwords Str::upper Str::ulid Str::unwrap Str::uuid Str::uuid7 Str::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
플루언트 문자열 (Fluent Strings)
after afterLast apa append ascii basename before beforeLast between betweenFirst camel charAt classBasename chopStart chopEnd contains containsAll counted decrypt deduplicate dirname doesntContain doesntEndWith doesntStartWith encrypt endsWith exactly excerpt explode finish fromBase64 hash headline initials inlineMarkdown is isAscii isEmpty isNotEmpty isJson isUlid isUrl isUuid kebab lcfirst length limit lower markdown mask match matchAll isMatch newLine padBoth padLeft padRight pipe plural position prepend remove repeat replace replaceArray replaceFirst replaceLast replaceMatches replaceStart replaceEnd scan singular slug snake split squish start startsWith stripTags studly substr substrReplace swap take tap test title toBase64 toHtmlString toUri transliterate trim ltrim rtrim ucfirst ucsplit ucwords unwrap upper when whenContains whenContainsAll whenDoesntEndWith whenDoesntStartWith whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words wrap
NOTE
아래는 목차 역할을 하는 메서드 목록입니다. 각 메서드에 대한 상세 설명과 예제 코드는 다음 섹션에서 이어집니다.
Strings
`__()` {.collection-method}
__ 함수는 언어 파일을 사용하여 주어진 번역 문자열 또는 번역 키를 번역합니다:
echo __('Welcome to our application');
echo __('messages.welcome');지정한 번역 문자열이나 키가 존재하지 않으면, __ 함수는 주어진 값을 그대로 반환합니다. 따라서 위 예제를 사용할 경우, 해당 번역 키가 존재하지 않으면 __ 함수는 messages.welcome을 반환하게 됩니다.
`class_basename()` {.collection-method}
class_basename 함수는 주어진 클래스에서 네임스페이스가 제거된 클래스 이름을 반환합니다:
$class = class_basename('Foo\Bar\Baz');
// Baz`e()` {.collection-method}
e 함수는 PHP의 htmlspecialchars 함수를 실행하며, 기본적으로 double_encode 옵션이 true로 설정되어 있습니다:
echo e('<html>foo</html>');
// <html>foo</html>`preg_replace_array()` {.collection-method}
preg_replace_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}
`Str::after` 메서드는 문자열에서 주어진 값 이후의 모든 내용을 반환합니다. 값이 문자열 내에 존재하지 않으면 전체 문자열이 반환됩니다:use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'`Str::afterLast()` {.collection-method}
Str::afterLast 메서드는 문자열에서 주어진 값이 마지막으로 등장한 이후의 모든 내용을 반환합니다. 값이 문자열 내에 존재하지 않으면 전체 문자열이 반환됩니다:
use Illuminate\Support\Str;
$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
// 'Controller'`Str::apa()` {.collection-method}
Str::apa 메서드는 주어진 문자열을 APA 가이드라인에 따라 타이틀 케이스로 변환합니다:
use Illuminate\Support\Str;
$title = Str::apa('Creating A Project');
// 'Creating a Project'`Str::ascii()` {.collection-method}
Str::ascii 메서드는 문자열을 ASCII 값으로 변환(음역)을 시도합니다:
use Illuminate\Support\Str;
$slice = Str::ascii('û');
// 'u'`Str::before()` {.collection-method}
Str::before 메서드는 문자열에서 주어진 값 이전의 모든 내용을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
`Str::beforeLast()` {.collection-method}
Str::beforeLast 메서드는 문자열에서 주어진 값이 마지막으로 나타나기 전까지의 모든 부분을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::beforeLast('This is my name', 'is');
// 'This '`Str::between()` {.collection-method}
Str::between 메서드는 두 값 사이에 있는 문자열의 부분을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::between('This is my name', 'This', 'name');
// ' is my '`Str::betweenFirst()` {.collection-method}
Str::betweenFirst 메서드는 두 값 사이에서 가능한 가장 작은 부분의 문자열을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
// 'a'`Str::camel()` {.collection-method}
Str::camel 메서드는 주어진 문자열을 camelCase로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// 'fooBar'`Str::charAt()` {.collection-method}
Str::charAt 메서드는 지정된 인덱스에 있는 문자를 반환합니다. 인덱스가 범위를 벗어난 경우 false가 반환됩니다:
use Illuminate\Support\Str;
$character = Str::charAt('This is my name.', 6);
// 's'`Str::chopStart()` {.collection-method}
`Str::chopStart` 메서드는 주어진 값이 문자열의 시작 부분에 나타나는 경우에만 해당 값의 첫 번째 발생을 제거합니다:use Illuminate\Support\Str;
$url = Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'두 번째 인수로 배열을 전달할 수도 있습니다. 문자열이 배열에 있는 값 중 하나로 시작하는 경우 해당 값이 문자열에서 제거됩니다:
use Illuminate\Support\Str;
$url = Str::chopStart('http://laravel.com', ['https://', 'http://']);
// 'laravel.com'`Str::chopEnd()` {.collection-method}
Str::chopEnd 메서드는 주어진 값이 문자열의 끝 부분에 나타나는 경우에만 해당 값의 마지막 발생을 제거합니다:
use Illuminate\Support\Str;
$url = Str::chopEnd('app/Models/Photograph.php', '.php');
// 'app/Models/Photograph'두 번째 인수로 배열을 전달할 수도 있습니다. 문자열이 배열에 있는 값 중 하나로 끝나는 경우 해당 값이 문자열에서 제거됩니다:
use Illuminate\Support\Str;
$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);
// 'laravel.com'`Str::contains()` {.collection-method}
Str::contains 메서드는 주어진 문자열이 주어진 값을 포함하는지 판단합니다. 기본적으로 이 메서드는 대소문자를 구분합니다:
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'my');
// trueuse Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', ['my', 'foo']);
// trueYou may disable case sensitivity by setting the ignoreCase argument to true:
use Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true);
// true`Str::convertCase()` {.collection-method}
The Str::convertCase method converts the given string to specified case:
use Illuminate\Support\Str;
use Illuminate\Support\Enums\Case;
$converted = Str::convertCase('Hello World', Case::Lower);
// hello world
$converted = Str::convertCase('Hello World', Case::Upper);
// HELLO WORLD`Str::deduplicate()` {.collection-method}
The Str::deduplicate method replaces consecutive instances of a character with a single instance of that character in the given string. By default, the method deduplicates whitespace characters:
use Illuminate\Support\Str;
$result = Str::deduplicate('The Laravel Framework');
// The Laravel FrameworkYou may also specify a different character to deduplicate by passing it in as the second argument to the method:
use Illuminate\Support\Str;
$result = Str::deduplicate('The---Laravel---Framework', '-');
// The-Laravel-Framework`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');
// trueYou 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::explode()` {.collection-method}
The Str::explode method splits a string by the given delimiter and returns a collection containing each section of the split string:
use Illuminate\Support\Str;
$collection = Str::explode('one, two, three', ', ');
// collect(['one', 'two', 'three'])$doesntContain = Str::doesntContain('This is name', ['my', 'framework']);
// trueignoreCase 인자를 true로 설정하면 대소문자 구분을 비활성화할 수 있습니다:
use Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true);
// true`Str::deduplicate()` {.collection-method}
Str::deduplicate 메서드는 주어진 문자열에서 연속된 문자 인스턴스를 해당 문자 하나로 대체합니다. 기본적으로 이 메서드는 공백을 중복 제거합니다:
use Illuminate\Support\Str;
$result = Str::deduplicate('The Laravel Framework');
// The Laravel Framework메서드의 두 번째 인자로 다른 문자를 전달하여 중복 제거할 문자를 지정할 수 있습니다:
use Illuminate\Support\Str;
$result = Str::deduplicate('The---Laravel---Framework', '-');
// The-Laravel-FrameworkStr::doesntEndWith() {.collection-method}
Str::doesntEndWith 메서드는 주어진 문자열이 주어진 값으로 끝나지 않는지 판단합니다:
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', 'dog');
// true값들의 배열을 전달하여 주어진 문자열이 배열 내 어떤 값으로도 끝나지 않는지 판단할 수도 있습니다:
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', ['this', 'foo']);
// true$result = Str::doesntEndWith('This is my name', ['name', 'foo']);
// false`Str::doesntStartWith()` {.collection-method}
Str::doesntStartWith 메서드는 주어진 문자열이 주어진 값으로 시작하지 않는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::doesntStartWith('This is my name', 'That');
// true가능한 값들의 배열을 전달하면, doesntStartWith 메서드는 문자열이 주어진 값 중 어느 것으로도 시작하지 않을 경우 true를 반환합니다:
$result = Str::doesntStartWith('This is my name', ['What', 'That', 'There']);
// true`Str::endsWith()` {.collection-method}
Str::endsWith 메서드는 주어진 문자열이 주어진 값으로 끝나는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::endsWith('This is my name', 'name');
// true배열로 여러 값을 전달하여 주어진 문자열이 배열 내의 값들 중 하나로 끝나는지도 확인할 수 있습니다:
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}
Str::excerpt 메서드는 주어진 문자열에서 특정 구문이 처음 등장하는 부분과 일치하는 발췌문을 추출합니다:
use Illuminate\Support\Str;
$excerpt = Str::excerpt('This is my name', 'my', [
'radius' => 3
]);
// '...is my na...'radius 옵션은 기본값이 100이며, 잘린 문자열의 양쪽에 표시될 문자 수를 정의할 수 있게 해줍니다.
또한 omission 옵션을 사용하여 잘린 문자열의 앞뒤에 붙일 문자열을 정의할 수 있습니다:
use Illuminate\Support\Str;
$excerpt = Str::excerpt('This is my name', 'name', [
'radius' => 3,
'omission' => '(...) '
]);
// '(...) my name'`Str::finish()` {.collection-method}
Str::finish 메서드는 문자열이 주어진 값으로 끝나지 않는 경우, 해당 값의 단일 인스턴스를 문자열에 추가합니다:
use Illuminate\Support\Str;
$adjusted = Str::finish('this/string', '/');
// this/string/
$adjusted = Str::finish('this/string/', '/');
// this/string/`Str::fromBase64()` {.collection-method}
Str::fromBase64 메서드는 주어진 Base64 문자열을 디코딩합니다:
use Illuminate\Support\Str;
$decoded = Str::fromBase64('TGFyYXZlbA==');
// Laravel`Str::headline()` {.collection-method}
Str::headline 메서드는 대소문자, 하이픈, 언더스코어로 구분된 문자열을 각 단어의 첫 글자가 대문자로 된 공백 구분 문자열로 변환합니다:
use Illuminate\Support\Str;
$headline = Str::headline('steve_jobs');
// Steve Jobs
$headline = Str::headline('EmailNotificationSent');
```php
// Email Notification Sent`Str::initials()` {.collection-method}
Str::initials 메서드는 주어진 문자열의 이니셜을 반환하며, 필요하다면 대문자로 변환할 수도 있습니다.
use Illuminate\Support\Str;
$initials = Str::initials('taylor otwell');
// to
$initials = Str::initials('taylor otwell', capitalize: true);
// TO`Str::inlineMarkdown()` {.collection-method}
Str::inlineMarkdown 메서드는 CommonMark를 사용하여 GitHub 스타일의 마크다운을 인라인 HTML로 변환합니다. 그러나 markdown 메서드와 달리, 생성된 모든 HTML을 블록 레벨 요소로 감싸지 않습니다.
use Illuminate\Support\Str;
$html = Str::inlineMarkdown('**Laravel**');
// <strong>Laravel</strong>마크다운 보안
기본적으로 마크다운은 원시 HTML을 지원하는데, 이를 원시 사용자 입력과 함께 사용하면 크로스 사이트 스크립팅(XSS) 취약점이 노출될 수 있습니다. CommonMark 보안 문서에 따르면, html_input 옵션을 사용해 원시 HTML을 이스케이프하거나 제거할 수 있으며, allow_unsafe_links 옵션을 사용해 안전하지 않은 링크의 허용 여부를 지정할 수 있습니다. 일부 원시 HTML을 허용해야 한다면, 컴파일된 마크다운을 HTML Purifier에 통과시켜야 합니다.
use Illuminate\Support\Str;
Str::inlineMarkdown('Inject: <script>alert("Hello XSS!");</script>', [
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// Inject: alert("Hello XSS!");`Str::is()` {.collection-method}
Str::is 메서드는 주어진 문자열이 주어진 패턴과 일치하는지 확인합니다. 별표(*)를 와일드카드 값으로 사용할 수 있습니다:
use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// falseignoreCase 인수를 true로 설정하여 대소문자 구분을 비활성화할 수 있습니다:
use Illuminate\Support\Str;
$matches = Str::is('*.jpg', 'photo.JPG', ignoreCase: true);
// true`Str::isAscii()` {.collection-method}
Str::isAscii 메서드는 주어진 문자열이 7비트 ASCII인지 확인합니다:
use Illuminate\Support\Str;
$isAscii = Str::isAscii('Taylor');
// true
$isAscii = Str::isAscii('ü');
// false`Str::isJson()` {.collection-method}
Str::isJson 메서드는 주어진 문자열이 유효한 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"}');
// falseStr::isUrl() {.collection-method}
Str::isUrl 메서드는 주어진 문자열이 유효한 URL인지 확인합니다:
use Illuminate\Support\Str;
$isUrl = Str::isUrl('http://example.com');
// true
$isUrl = Str::isUrl('laravel');
// falseisUrl 메서드는 광범위한 프로토콜을 유효한 것으로 간주합니다. 하지만 isUrl 메서드에 프로토콜을 전달하여 유효한 것으로 간주할 프로토콜을 지정할 수 있습니다:
$isUrl = Str::isUrl('http://example.com', ['http', 'https']);`Str::isUlid()` {.collection-method}
Str::isUlid 메서드는 주어진 문자열이 유효한 ULID인지 판단합니다:
use Illuminate\Support\Str;
$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
// true
$isUlid = Str::isUlid('laravel');
// false`Str::isUuid()` {.collection-method}
Str::isUuid 메서드는 주어진 문자열이 유효한 UUID인지 판단합니다:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
// true
$isUuid = Str::isUuid('laravel');
// false주어진 UUID가 버전(1, 3, 4, 5, 6, 7, 또는 8)별 UUID 사양과 일치하는지도 검증할 수 있습니다:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4);
// true
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1);
// false`Str::kebab()` {.collection-method}
Str::kebab 메서드는 주어진 문자열을 kebab-case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-bar`Str::lcfirst()` {.collection-method}
`Str::length()` {.collection-method}
Str::length 메서드는 주어진 문자열의 길이를 반환합니다:
use Illuminate\Support\Str;
$length = Str::length('Laravel');
// 7`Str::limit()` {.collection-method}
Str::limit 메서드는 주어진 문자열을 지정한 길이로 자릅니다:
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...세 번째 인수를 전달하면 잘린 문자열의 끝에 붙는 문자열을 변경할 수 있습니다:
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)문자열을 자를 때 완전한 단어를 유지하고 싶다면 preserveWords 인수를 사용할 수 있습니다. 이 인수가 true이면, 문자열은 가장 가까운 완전한 단어 경계까지 잘립니다:
$truncated = Str::limit('The quick brown fox', 12, preserveWords: true);
// The quick...`Str::lower()` {.collection-method}
Str::lower 메서드는 주어진 문자열을 소문자로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::lower('LARAVEL');
// laravelIf needed, you may provide negative numbers as the third or fourth 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
$string = Str::mask('taylor@example.com', '*', 4, -4);
// tayl**********.com`Str::match()` {.collection-method}
The Str::match method will return the portion of a string that matches a given regular expression pattern:
use Illuminate\Support\Str;
$result = Str::match('/bar/', 'foo bar');
// 'bar'
$result = Str::match('/foo (.*)/', 'foo bar');
// 'bar'`Str::isMatch()` {.collection-method}
The Str::isMatch method determines if a string matches a given regular expression pattern:
use Illuminate\Support\Str;
$result = Str::isMatch('/foo (.*)/', 'foo bar');
// true
$result = Str::isMatch('/foo (.*)/', 'laravel');
// false`Str::matchAll()` {.collection-method}
The Str::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::matchAll('/bar/', 'bar foo bar');
// collect(['bar', 'bar'])If you specify a matching group within the expression, Laravel will return a collection of that group's matches:
$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly');
// collect(['un', 'ly']);If no matches are found, an empty collection will be returned.
`Str::numbers()` {.collection-method}
The Str::numbers method removes all non-numeric characters from a string:
use Illuminate\Support\Str;
$result = Str::numbers('(555) 123-4567');
// 5551234567
$result = Str::numbers('L4r4v3l!');
// 443`Str::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::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');
// childrenYou may provide an integer as the 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');
// UserFeedbackYou may provide an integer as the 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::pluralPascal()` {.collection-method}
The Str::pluralPascal method converts a singular word string formatted in Pascal case to its plural form. This function supports any of the languages support by Laravel's pluralizer:
use Illuminate\Support\Str;
$plural = Str::pluralPascal('VerifiedHuman');
// VerifiedHumans
$plural = Str::pluralPascal('UserFeedback');
// UserFeedbackYou may provide an integer as the second argument to the function to retrieve the singular or plural form of the string:
use Illuminate\Support\Str;
$plural = Str::pluralPascal('VerifiedHuman', 2);
// VerifiedHumans
$singular = Str::pluralPascal('VerifiedHuman', 1);
// VerifiedHuman`Str::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);During testing, it may be useful to "fake" the value that is returned by the Str::random method. To accomplish this, you may use the createRandomStringsUsing method:
Str::createRandomStringsUsing(function () {
return 'fake-random-string';
});To instruct the string helper to return to generating random strings normally, you may invoke the createRandomStringsNormally method:
Str::createRandomStringsNormally();`Str::repeat()` {.collection-method}
The Str::repeat method repeats the given string:
use Illuminate\Support\Str;
$repeated = Str::repeat('a', 5);
// aaaaa`Str::replace()` {.collection-method}
The Str::replace method replaces a given string within the string:
use Illuminate\Support\Str;
$string = 'Laravel 10.x';
$replaced = Str::replace('10.x', '11.x', $string);
// Laravel 11.xThe 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 fox jumps over the lazy dog');
// a quick 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 fox jumps over the lazy dog');
// the quick 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');
// trueIf 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::take()` {.collection-method}
The Str::take method returns a specified number of characters from the beginning of a string:
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build`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::toBase64()` {.collection-method}
The Str::toBase64 method converts the given string to Base64:
use Illuminate\Support\Str;
$base64 = Str::toBase64('Laravel');
// TGFyYXZlbA==`Str::trim()` {.collection-method}
The Str::trim method strips whitespace (or other characters) from the beginning and end of the given string. Unlike PHP's native trim function, the Str::trim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::trim(' foo bar ');
// 'foo bar'`Str::ltrim()` {.collection-method}
The Str::ltrim method strips whitespace (or other characters) from the beginning of the given string. Unlike PHP's native ltrim function, the Str::ltrim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::ltrim(' foo bar ');
// 'foo bar '`Str::rtrim()` {.collection-method}
The Str::rtrim method strips whitespace (or other characters) from the end of the given string. Unlike PHP's native rtrim function, the Str::rtrim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::rtrim(' foo bar ');
// ' foo bar'`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();
// 01gd6r360bp37zj17nxb55yv40If you would like to retrieve a 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;
$date = Carbon::createFromId((string) Str::ulid());During testing, it may be useful to "fake" the value that is returned by the Str::ulid method. To accomplish this, you may use the createUlidsUsing method:
use Symfony\Component\Uid\Ulid;
Str::createUlidsUsing(function () {
return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});To instruct the ulid method to return to generating ULIDs normally, you may invoke the createUlidsNormally method:
Str::createUlidsNormally();`Str::unwrap()` {.collection-method}
The Str::unwrap method removes the specified strings from the beginning and end of a given string:
use Illuminate\Support\Str;
Str::unwrap('-Laravel-', '-');
// Laravel
Str::unwrap('{framework: "Laravel"}', '{', '}');
// framework: "Laravel"`Str::uuid()` {.collection-method}
The Str::uuid method generates a UUID (version 4):
use Illuminate\Support\Str;
return (string) Str::uuid();During testing, it may be useful to "fake" the value that is returned by the Str::uuid method. To accomplish this, you may use the createUuidsUsing method:
use Ramsey\Uuid\Uuid;
Str::createUuidsUsing(function () {
return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');
});To instruct the uuid method to return to generating UUIDs normally, you may invoke the createUuidsNormally method:
Str::createUuidsNormally();`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: "\n");
/*
The quick brown fox
jumped over the lazy
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');
// $string->append(' 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'
If needed, you may 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:
```php
$string = Str::mask('taylor@example.com', '*', -15, 3);
// tay***@example.com`Str::match()` {.collection-method}
Str::match 메서드는 주어진 정규 표현식 패턴과 일치하는 문자열 부분을 반환합니다:
use Illuminate\Support\Str;
$result = Str::match('/bar/', 'foo bar');
// 'bar'
$result = Str::match('/foo (.*)/', 'foo bar');
// 'bar'`Str::matchAll()` {.collection-method}
Str::matchAll 메서드는 주어진 정규 표현식 패턴과 일치하는 문자열 부분을 담은 컬렉션을 반환합니다:
use Illuminate\Support\Str;
$result = Str::matchAll('/bar/', 'bar foo bar');
// collect(['bar', 'bar'])표현식 내에 매칭 그룹을 지정하면, 라라벨은 첫 번째 매칭 그룹의 매치 결과를 담은 컬렉션을 반환합니다:
use Illuminate\Support\Str;
$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly');
// collect(['un', 'ly']);일치하는 항목이 없으면 빈 컬렉션이 반환됩니다.
`Str::isMatch()` {.collection-method}
Str::isMatch 메서드는 문자열이 주어진 정규 표현식과 일치하면 true를 반환합니다:
use Illuminate\Support\Str;`Str::orderedUuid()` {.collection-method}
Str::orderedUuid 메서드는 인덱싱된 데이터베이스 컬럼에 효율적으로 저장할 수 있는 "타임스탬프 우선" UUID를 생성합니다. 이 메서드를 사용해 생성된 각 UUID는 이전에 이 메서드를 사용해 생성된 UUID 뒤에 정렬됩니다:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();`Str::padBoth()` {.collection-method}
Str::padBoth 메서드는 PHP의 str_pad 함수를 감싸는 메서드로, 문자열의 양쪽을 다른 문자열로 채워서 최종 문자열이 원하는 길이에 도달하도록 합니다:
use Illuminate\Support\Str;
$padded = Str::padBoth('James', 10, '_');
// '__James___'
$padded = Str::padBoth('James', 10);
// ' James '`Str::padLeft()` {.collection-method}
Str::padLeft 메서드는 PHP의 str_pad 함수를 감싸는 메서드로, 문자열의 왼쪽을 다른 문자열로 채워서 최종 문자열이 원하는 길이에 도달하도록 합니다:
use Illuminate\Support\Str;
$padded = Str::padLeft('James', 10, '-=');
// '-=-=-James'
$padded = Str::padLeft('James', 10);
// ' James'`Str::padRight()` {.collection-method}
$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:
```php
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 supported by Laravel's pluralizer:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman');
// VerifiedHumans
$plural = Str::pluralStudly('UserFeedback');
// UserFeedbackYou 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::pluralPascal()` {.collection-method}
The Str::pluralPascal method converts a singular word string formatted in Pascal case to its plural form. This function supports any of the languages supported by Laravel's pluralizer. This method is an alias for the Str::pluralStudly method:
use Illuminate\Support\Str;
$plural = Str::pluralPascal('VerifiedHuman');
// VerifiedHumans
$plural = Str::pluralPascal('UserFeedback');
// UserFeedbackYou 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::pluralPascal('VerifiedHuman', 2);
// VerifiedHumans
$singular = Str::pluralPascal('VerifiedHuman', 1);
// VerifiedHuman`Str::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);During testing, it may be useful to "fake" the value that is returned by the Str::random method. To accomplish this, you may use the createRandomStringsUsing method:
Str::createRandomStringsUsing(function () {
return 'fake-random-string';
});To instruct the random string generator to return to generating random strings normally, you may invoke the createRandomStringsNormally method:
Str::createRandomStringsNormally();`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 10.x';
$replaced = Str::replace('10.x', '11.x', $string);
// Laravel 11.xThe replace method also accepts a caseSensitive argument. By default, the replace method is case sensitive:
Str::replace('Framework', 'Laravel', 'PHP Framework', 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 fox jumps over the lazy dog');
// a quick 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 fox jumps over the lazy dog');
// the quick 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 supported 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::split()` {.collection-method}
The Str::split method splits a string into an array using a regular expression:
use Illuminate\Support\Str;
$segments = Str::split('one, two, three', '/[\s,]+/');
// ["one", "two", "three"]`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');
// trueIf 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::take()` {.collection-method}
The Str::take method returns a specified number of characters from the beginning of a string:
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build`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$plural = Str::plural('car');
// cars
$plural = Str::plural('child');
// children두 번째 인수로 정수를 제공하면 문자열의 단수형 또는 복수형을 가져올 수 있습니다:
use Illuminate\Support\Str;
$plural = Str::plural('child', 2);
// children
$singular = Str::plural('child', 1);
// childprependCount 인수를 제공하면 포맷된 $count를 복수형 문자열 앞에 붙일 수 있습니다:
use Illuminate\Support\Str;
$label = Str::plural('car', 1000, prependCount: true);
// 1,000 cars`Str::pluralStudly()` {.collection-method}
Str::pluralStudly 메서드는 studly caps case로 포맷된 단수형 단어 문자열을 복수형으로 변환합니다. 이 함수는 Laravel의 복수화 도구가 지원하는 모든 언어를 지원합니다:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman');
// VerifiedHumans
$plural = Str::pluralStudly('UserFeedback');
// UserFeedback두 번째 인수로 정수를 제공하면 문자열의 단수형 또는 복수형을 가져올 수 있습니다:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman', 2);
// VerifiedHumans
$singular = Str::pluralStudly('VerifiedHuman', 1);
// VerifiedHuman`Str::position()` {.collection-method}
`Str::position` 메서드는 문자열에서 부분 문자열이 처음 등장하는 위치를 반환합니다. 주어진 문자열에 부분 문자열이 존재하지 않으면 `false`가 반환됩니다:use Illuminate\Support\Str;
$position = Str::position('Hello, World!', 'Hello');
// 0
$position = Str::position('Hello, World!', 'W');
// 7`Str::random()` {.collection-method}
Str::random 메서드는 지정된 길이의 무작위 문자열을 생성합니다. 이 함수는 PHP의 random_bytes 함수를 사용합니다:
use Illuminate\Support\Str;
$random = Str::random(40);테스트 중에는 Str::random 메서드가 반환하는 값을 "가짜로" 만드는 것이 유용할 수 있습니다. 이를 위해 createRandomStringsUsing 메서드를 사용할 수 있습니다:
Str::createRandomStringsUsing(function () {
return 'fake-random-string';
});random 메서드가 다시 정상적으로 무작위 문자열을 생성하도록 하려면 createRandomStringsNormally 메서드를 호출하면 됩니다:
Str::createRandomStringsNormally();Str::remove() {.collection-method}
Str::remove 메서드는 주어진 값 또는 값의 배열을 문자열에서 제거합니다:
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.use Illuminate\Support\Str;
$replaced = Str::replaceFirst('the', 'a', 'the quick fox jumps over the lazy dog');
// a quick fox jumps over the lazy dog
<h4 id="method-fluent-str-is">`Str::replaceLast()` {.collection-method}</h4>
The `Str::replaceLast` method replaces the last occurrence of a given value in a string:
```php
use Illuminate\Support\Str;
$replaced = Str::replaceLast('the', 'a', 'the quick fox jumps over the lazy dog');
// the quick 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::split()` {.collection-method}
The Str::split method splits a string into an array using a regular expression:
use Illuminate\Support\Str;
$segments = Str::split('one, two, three', '/[\s,]+/');
// ["one", "two", "three"]`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');
// trueIf 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::take() {.collection-method}
The Str::take method returns a specified number of characters from the beginning of a string:
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build`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::toBase64()` {.collection-method}
The Str::toBase64 method converts the given string to Base64:
use Illuminate\Support\Str;
$base64 = Str::toBase64('Laravel');
// TGFyYXZlbA==`Str::trim()` {.collection-method}
The Str::trim method strips whitespace (or other characters) from the beginning and end of the given string. Unlike PHP's native trim function, the Str::trim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::trim(' foo bar ');
// 'foo bar'`Str::ltrim()` {.collection-method}
The Str::ltrim method strips whitespace (or other characters) from the beginning of the given string. Unlike PHP's native ltrim function, the Str::ltrim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::ltrim(' foo bar ');
// 'foo bar '`Str::rtrim()` {.collection-method}
The Str::rtrim method strips whitespace (or other characters) from the end of the given string. Unlike PHP's native rtrim function, the Str::rtrim method also removes unicode whitespace characters:
use Illuminate\Support\Str;
$string = Str::rtrim(' foo bar ');
// ' foo bar'`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::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: "\n");
/*
The quick brown fox
jumped over the lazy
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');
echo $string->upper();
// TAYLORIf no argument is provided to the str function, the function returns an instance of Illuminate\Support\Str:
echo str()->plural('word');
// words`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.
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}
Str::replaceLast 메서드는 문자열에서 주어진 값이 마지막으로 나타나는 부분을 대체합니다:
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::replaceMatches()` {.collection-method}
Str::replaceMatches 메서드는 패턴과 일치하는 문자열의 모든 부분을 주어진 대체 문자열로 교체합니다:
use Illuminate\Support\Str;
$replaced = Str::replaceMatches(
pattern: '/[^A-Za-z0-9]++/',
replace: '',
subject: '(+1) 501-555-1000'
);
// '15015551000'replaceMatches 메서드는 주어진 패턴과 일치하는 문자열의 각 부분과 함께 호출되는 클로저도 인자로 받을 수 있으며, 이를 통해 클로저 내부에서 대체 로직을 수행하고 대체된 값을 반환할 수 있습니다:
use Illuminate\Support\Str;
$replaced = Str::replaceMatches('/\d/', function (array $matches) {
return '['.$matches[0].']';
}, '123');
// '[1][2][3]'`Str::replaceStart()` {.collection-method}
`Str::replaceStart` 메서드는 주어진 값이 문자열의 시작 부분에 나타나는 경우에만 첫 번째로 발견된 값을 대체합니다: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}
Str::replaceEnd 메서드는 주어진 값이 문자열의 끝 부분에 나타나는 경우에만 마지막으로 발견된 값을 대체합니다:
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}
Str::reverse 메서드는 주어진 문자열을 뒤집습니다:
use Illuminate\Support\Str;
$reversed = Str::reverse('Hello World');
// dlroW olleH`Str::singular()` {.collection-method}
Str::singular 메서드는 문자열을 단수형으로 변환합니다. 이 함수는 라라벨의 복수화 처리기가 지원하는 모든 언어를 지원합니다:
use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// child`Str::slug()` {.collection-method}
`Str::slug` 메서드는 주어진 문자열로부터 URL에 적합한 "슬러그(slug)"를 생성합니다:use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');
// laravel-5-framework`Str::snake()` {.collection-method}
Str::snake 메서드는 주어진 문자열을 snake_case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::snake('fooBar');
// foo_bar
$converted = Str::snake('fooBar', '-');
// foo-bar`Str::squish()` {.collection-method}
Str::squish 메서드는 단어 사이의 불필요한 공백을 포함하여 문자열에서 모든 불필요한 공백을 제거합니다:
use Illuminate\Support\Str;
$string = Str::squish(' laravel framework ');
// laravel framework`Str::start()` {.collection-method}
Str::start 메서드는 문자열이 주어진 값으로 시작하지 않는 경우, 해당 값을 한 번만 추가합니다:
use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/string`Str::startsWith()` {.collection-method}
Str::startsWith 메서드는 주어진 문자열이 주어진 값으로 시작하는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', 'This');
// true값의 배열이 전달되면, startsWith 메서드는 주어진 값 중 하나로 문자열이 시작하면 true를 반환합니다:
$result = Str::startsWith('This is my name', ['This', 'That', 'There']);
// true`Str::studly()` {.collection-method}
Str::studly 메서드는 주어진 문자열을 StudlyCase로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBar`Str::substr()` {.collection-method}
Str::substr 메서드는 start와 length 매개변수로 지정된 문자열의 일부분을 반환합니다:
use Illuminate\Support\Str;
$converted = Str::substr('The Laravel Framework', 4, 7);
// Laravel`Str::substrCount()` {.collection-method}
Str::substrCount 메서드는 주어진 문자열에서 주어진 값이 등장하는 횟수를 반환합니다:
use Illuminate\Support\Str;
$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
// 2`Str::substrReplace()` {.collection-method}
`Str::substrReplace` 메서드는 세 번째 인수로 지정한 위치에서 시작하여 네 번째 인수로 지정한 문자 수만큼 문자열의 일부분을 대체합니다. 메서드의 네 번째 인수로 `0`을 전달하면 문자열의 기존 문자를 대체하지 않고 지정된 위치에 문자열을 삽입합니다:use Illuminate\Support\Str;
$result = Str::substrReplace('1300', ':', 2);
// 13:
$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00`Str::swap()` {.collection-method}
Str::swap 메서드는 PHP의 strtr 함수를 사용하여 주어진 문자열 내의 여러 값을 대체합니다:
use Illuminate\Support\Str;
$string = Str::swap([
'Tacos' => 'Burritos',
'great' => 'fantastic',
], 'Tacos are great!');
// Burritos are fantastic!`Str::take()` {.collection-method}
Str::take 메서드는 문자열의 시작 부분부터 지정된 개수의 문자를 반환합니다:
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build`Str::title()` {.collection-method}
Str::title 메서드는 주어진 문자열을 Title Case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct Case`Str::toBase64()` {.collection-method}
`Str::toBase64` 메서드는 주어진 문자열을 Base64로 변환합니다:use Illuminate\Support\Str;
$base64 = Str::toBase64('Laravel');
// TGFyYXZlbA==`Str::transliterate()` {.collection-method}
Str::transliterate 메서드는 주어진 문자열을 가장 가까운 ASCII 표현으로 변환하려고 시도합니다:
use Illuminate\Support\Str;
$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
// 'test@laravel.com'`Str::trim()` {.collection-method}
Str::trim 메서드는 주어진 문자열의 시작과 끝에서 공백(또는 다른 문자)을 제거합니다. PHP의 기본 trim 함수와 달리, Str::trim 메서드는 유니코드 공백 문자도 제거합니다:
use Illuminate\Support\Str;
$string = Str::trim(' foo bar ');
// 'foo bar'`Str::ltrim()` {.collection-method}
Str::ltrim 메서드는 주어진 문자열의 시작 부분에서 공백(또는 다른 문자)을 제거합니다. PHP의 기본 ltrim 함수와 달리, Str::ltrim 메서드는 유니코드 공백 문자도 제거합니다:
use Illuminate\Support\Str;
$string = Str::ltrim(' foo bar ');
// 'foo bar '`Str::rtrim()` {.collection-method}
`Str::rtrim` 메서드는 주어진 문자열의 끝에서 공백(또는 다른 문자)을 제거합니다. PHP의 네이티브 `rtrim` 함수와 달리, `Str::rtrim` 메서드는 유니코드 공백 문자도 제거합니다:use Illuminate\Support\Str;
$string = Str::rtrim(' foo bar ');
// ' foo bar'`Str::ucfirst()` {.collection-method}
Str::ucfirst 메서드는 주어진 문자열의 첫 번째 문자를 대문자로 변환하여 반환합니다:
use Illuminate\Support\Str;
$string = Str::ucfirst('foo bar');
// Foo bar`Str::ucsplit()` {.collection-method}
Str::ucsplit 메서드는 주어진 문자열을 대문자를 기준으로 배열로 분리합니다:
use Illuminate\Support\Str;
$segments = Str::ucsplit('FooBar');
// [0 => 'Foo', 1 => 'Bar']`Str::ucwords()` {.collection-method}
Str::ucwords 메서드는 주어진 문자열에서 각 단어의 첫 번째 문자를 대문자로 변환합니다:
use Illuminate\Support\Str;
$string = Str::ucwords('laravel framework');
// Laravel Framework`Str::upper()` {.collection-method}
Str::upper 메서드는 주어진 문자열을 대문자로 변환합니다:
use Illuminate\Support\Str;
$string = Str::upper('laravel');
// LARAVEL`Str::ulid()` {.collection-method}
`Str::ulid` 메서드는 압축된 시간 순서 기반의 고유 식별자인 ULID를 생성합니다:use Illuminate\Support\Str;
return (string) Str::ulid();
// 01gd6r360bp37zj17nxb55yv40주어진 ULID가 생성된 날짜와 시간을 나타내는 Illuminate\Support\Carbon 날짜 인스턴스를 가져오고 싶다면, 라라벨의 Carbon 통합에서 제공하는 createFromId 메서드를 사용할 수 있습니다:
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
$date = Carbon::createFromId((string) Str::ulid());테스트하는 동안, Str::ulid 메서드가 반환하는 값을 "가짜로" 만드는 것이 유용할 수 있습니다. 이를 위해 createUlidsUsing 메서드를 사용할 수 있습니다:
use Symfony\Component\Uid\Ulid;
Str::createUlidsUsing(function () {
return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});ulid 메서드가 다시 정상적으로 ULID를 생성하도록 하려면, createUlidsNormally 메서드를 호출하면 됩니다:
Str::createUlidsNormally();`Str::unwrap()` {.collection-method}
Str::unwrap 메서드는 주어진 문자열의 시작과 끝에서 지정한 문자열을 제거합니다:
use Illuminate\Support\Str;
Str::unwrap('-Laravel-', '-');
// Laravel
Str::unwrap('{framework: "Laravel"}', '{', '}');
// framework: "Laravel"`Str::uuid()` {.collection-method}
Str::uuid 메서드는 UUID(버전 4)를 생성합니다:
use Illuminate\Support\Str;
return (string) Str::uuid();
테스트 중에는 `Str::uuid` 메서드가 반환하는 값을 "가짜로" 만드는 것이 유용할 수 있습니다. 이를 위해 `createUuidsUsing` 메서드를 사용할 수 있습니다:
```php
use Ramsey\Uuid\Uuid;
Str::createUuidsUsing(function () {
return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');
});uuid 메서드가 다시 정상적으로 UUID를 생성하도록 지시하려면 createUuidsNormally 메서드를 호출하면 됩니다:
Str::createUuidsNormally();`Str::uuid7()` {.collection-method}
Str::uuid7 메서드는 UUID(버전 7)를 생성합니다:
use Illuminate\Support\Str;
return (string) Str::uuid7();정렬된 UUID를 생성하는 데 사용할 DateTimeInterface를 선택적 매개변수로 전달할 수 있습니다:
return (string) Str::uuid7(time: now());`Str::wordCount()` {.collection-method}
Str::wordCount 메서드는 문자열에 포함된 단어의 수를 반환합니다:
use Illuminate\Support\Str;
Str::wordCount('Hello, world!'); // 2`Str::wordWrap()` {.collection-method}
Str::wordWrap 메서드는 문자열을 지정된 문자 수만큼 줄바꿈합니다:
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.
*/
<h4 id="method-fluent-str-ucwords">`Str::words()` {.collection-method}</h4>
`Str::words` 메서드는 문자열의 단어 수를 제한합니다. 이 메서드의 세 번째 인수로 추가 문자열을 전달하면, 잘린 문자열 끝에 어떤 문자열을 덧붙일지 지정할 수 있습니다:
```php
use Illuminate\Support\Str;
return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// Perfectly balanced, as >>>`Str::wrap()` {.collection-method}
Str::wrap 메서드는 주어진 문자열을 추가 문자열 또는 한 쌍의 문자열로 감쌉니다:
use Illuminate\Support\Str;
Str::wrap('Laravel', '"');
// "Laravel"
Str::wrap('is', before: 'This ', after: ' Laravel!');
// This is Laravel!`str()` {.collection-method}
str 함수는 주어진 문자열의 새로운 Illuminate\Support\Stringable 인스턴스를 반환합니다. 이 함수는 Str::of 메서드와 동일합니다:
$string = str('Taylor')->append(' Otwell');
// 'Taylor Otwell'str 함수에 인수가 전달되지 않으면, 이 함수는 Illuminate\Support\Str의 인스턴스를 반환합니다:
$snake = str()->snake('FooBar');
// 'foo_bar'`trans()` {.collection-method}
trans 함수는 언어 파일을 사용하여 주어진 번역 키를 번역합니다:
echo trans('messages.welcome');지정한 번역 키가 존재하지 않으면, trans 함수는 주어진 키를 반환합니다. 즉, 위 예제를 사용할 때 번역 키가 존재하지 않으면 trans 함수는 messages.welcome을 반환합니다.
`trans_choice()` {.collection-method}
trans_choice 함수는 주어진 번역 키를 복수형 처리와 함께 번역합니다:
echo trans_choice('messages.notifications', $unreadCount);지정한 번역 키가 존재하지 않으면, trans_choice 함수는 주어진 키를 반환합니다. 즉, 위 예제를 사용할 때 번역 키가 존재하지 않으면 trans_choice 함수는 messages.notifications를 반환합니다.
Fluent Strings
Fluent strings는 전통적인 문자열 조작 방식보다 더 읽기 쉬운 문법을 사용하여 여러 문자열 작업을 체이닝할 수 있도록 해주는, 보다 유연하고 객체 지향적인 문자열 작업 인터페이스를 제공합니다.
`after` {.collection-method}
after 메서드는 문자열 내에서 주어진 값 이후의 모든 부분을 반환합니다. 해당 값이 문자열 내에 존재하지 않으면 전체 문자열이 반환됩니다:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->after('This is');
// ' my name'`afterLast` {.collection-method}
afterLast 메서드는 문자열 내에서 주어진 값이 마지막으로 등장한 이후의 모든 부분을 반환합니다. 해당 값이 문자열 내에 존재하지 않으면 전체 문자열이 반환됩니다:
use Illuminate\Support\Str;
$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');
// 'Controller'`apa` {.collection-method}
apa 메서드는 주어진 문자열을 APA 가이드라인에 따른 타이틀 케이스로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('a nice title uses the correct case')->apa();
// A Nice Title Uses the Correct Case`append` {.collection-method}
append 메서드는 주어진 값들을 문자열에 추가합니다:
use Illuminate\Support\Str;
$string = Str::of('Taylor')->append(' Otwell');
// 'Taylor Otwell'`ascii` {.collection-method}
ascii 메서드는 문자열을 ASCII 값으로 음역하려고 시도합니다:
use Illuminate\Support\Str;
$string = Str::of('ü')->ascii();
// 'u'`basename` {.collection-method}
basename 메서드는 주어진 문자열의 마지막 이름 구성 요소를 반환합니다:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->basename();
// 'baz'필요하다면, 마지막 구성 요소에서 제거할 "확장자"를 지정할 수 있습니다:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');
// 'baz'`before` {.collection-method}
before 메서드는 문자열에서 주어진 값 이전의 모든 것을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->before('my name');
// 'This is '`beforeLast` {.collection-method}
beforeLast 메서드는 문자열에서 주어진 값이 마지막으로 등장하기 이전의 모든 것을 반환합니다:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->beforeLast('is');
// 'This '`between` {.collection-method}
`between` 메서드는 두 값 사이에 있는 문자열의 부분을 반환합니다:use Illuminate\Support\Str;
$converted = Str::of('This is my name')->between('This', 'name');
// ' is my '`betweenFirst` {.collection-method}
betweenFirst 메서드는 두 값 사이에서 가능한 가장 작은 문자열 부분을 반환합니다:
use Illuminate\Support\Str;
$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');
// 'a'`camel` {.collection-method}
camel 메서드는 주어진 문자열을 camelCase로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->camel();
// 'fooBar'`charAt` {.collection-method}
charAt 메서드는 지정된 인덱스에 있는 문자를 반환합니다. 인덱스가 범위를 벗어난 경우 false가 반환됩니다:
use Illuminate\Support\Str;
$character = Str::of('This is my name.')->charAt(6);
// 's'`classBasename` {.collection-method}
classBasename 메서드는 주어진 클래스에서 네임스페이스를 제거한 클래스명을 반환합니다:
use Illuminate\Support\Str;
$class = Str::of('Foo\Bar\Baz')->classBasename();
// 'Baz'`chopStart` {.collection-method}
`chopStart` 메서드는 주어진 값이 문자열의 시작 부분에 나타나는 경우에만 해당 값의 첫 번째 발생을 제거합니다:use Illuminate\Support\Str;
$url = Str::of('https://laravel.com')->chopStart('https://');
// 'laravel.com'배열을 전달할 수도 있습니다. 문자열이 배열에 있는 값 중 하나로 시작하면 해당 값이 문자열에서 제거됩니다:
use Illuminate\Support\Str;
$url = Str::of('http://laravel.com')->chopStart(['https://', 'http://']);
// 'laravel.com'`chopEnd` {.collection-method}
chopEnd 메서드는 주어진 값이 문자열의 끝 부분에 나타나는 경우에만 해당 값의 마지막 발생을 제거합니다:
use Illuminate\Support\Str;
$url = Str::of('https://laravel.com')->chopEnd('.com');
// 'https://laravel'배열을 전달할 수도 있습니다. 문자열이 배열에 있는 값 중 하나로 끝나면 해당 값이 문자열에서 제거됩니다:
use Illuminate\Support\Str;
$url = Str::of('http://laravel.com')->chopEnd(['.com', '.io']);
// 'http://laravel'`contains` {.collection-method}
contains 메서드는 주어진 문자열에 주어진 값이 포함되어 있는지 확인합니다. 기본적으로 이 메서드는 대소문자를 구분합니다:
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains('my');
// true주어진 값들이 배열에 있는 값 중 하나라도 포함되어 있는지 확인하기 위해 값들의 배열을 전달할 수도 있습니다:
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains(['my', 'foo']);
// trueignoreCase 인수를 true로 설정하여 대소문자 구분을 비활성화할 수 있습니다:
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains('MY', ignoreCase: true);
// truecontainsAll {.collection-method}
containsAll 메서드는 주어진 문자열이 주어진 배열에 있는 모든 값을 포함하는지 확인합니다:
use Illuminate\Support\Str;
$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);
// trueignoreCase 인수를 true로 설정하여 대소문자 구분을 비활성화할 수 있습니다:
use Illuminate\Support\Str;
$containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);
// truedecrypt {.collection-method}
decrypt 메서드는 암호화된 문자열을 복호화합니다:
use Illuminate\Support\Str;
$decrypted = $encrypted->decrypt();
// 'secret'decrypt의 반대 동작은 encrypt 메서드를 참고하세요.
deduplicate {.collection-method}
deduplicate 메서드는 주어진 문자열에서 연속된 문자 인스턴스를 해당 문자의 단일 인스턴스로 치환합니다. 기본적으로 이 메서드는 공백을 중복 제거합니다:
use Illuminate\Support\Str;
$result = Str::of('The Laravel Framework')->deduplicate();
// The Laravel Framework메서드의 두 번째 인수로 다른 문자를 전달하여 중복 제거할 문자를 지정할 수 있습니다:
use Illuminate\Support\Str;
$result = Str::of('The---Laravel---Framework')->deduplicate('-');
// The-Laravel-Frameworkdirname {.collection-method}
dirname 메서드는 주어진 문자열의 상위 디렉터리 부분을 반환합니다:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->dirname();
// '/foo/bar'필요한 경우, 문자열에서 잘라내고자 하는 디렉터리 레벨의 수를 지정할 수 있습니다:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->dirname(2);
// '/foo'doesntContain() {.collection-method}
doesntContain 메서드는 주어진 문자열이 주어진 값을 포함하지 않는지 확인합니다. 이 메서드는 contains 메서드의 반대입니다. 기본적으로 이 메서드는 대소문자를 구분합니다:
use Illuminate\Support\Str;
$doesntContain = Str::of('This is name')->doesntContain('my');
// true값 배열을 전달하여 주어진 문자열이 배열 안의 어떤 값도 포함하지 않는지 확인할 수도 있습니다:
use Illuminate\Support\Str;
$doesntContain = Str::of('This is name')->doesntContain(['my', 'framework']);
// trueignoreCase 인수를 true로 설정하면 대소문자 구분을 비활성화할 수 있습니다:
use Illuminate\Support\Str;
$doesntContain = Str::of('This is my name')->doesntContain('MY', ignoreCase: true);
// falsedoesntEndWith {.collection-method}
doesntEndWith 메서드는 주어진 문자열이 주어진 값으로 끝나지 않는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith('dog');
// true값 배열을 전달하여 주어진 문자열이 배열 안의 어떤 값으로도 끝나지 않는지 확인할 수도 있습니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith(['this', 'foo']);
// true
$result = Str::of('This is my name')->doesntEndWith(['name', 'foo']);
// falsedoesntStartWith {.collection-method}
doesntStartWith 메서드는 주어진 문자열이 주어진 값으로 시작하지 않는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith('That');
// true배열을 전달하여 주어진 문자열이 배열 내 값들 중 어느 것으로도 시작하지 않는지 확인할 수도 있습니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);
// trueencrypt {.collection-method}
encrypt 메서드는 문자열을 암호화합니다:
use Illuminate\Support\Str;
$encrypted = Str::of('secret')->encrypt();encrypt의 반대 작업은 decrypt 메서드를 참고하세요.
endsWith {.collection-method}
endsWith 메서드는 주어진 문자열이 지정된 값으로 끝나는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->endsWith('name');
// true배열을 전달하여 주어진 문자열이 배열 내 값들 중 어느 것으로 끝나는지 확인할 수도 있습니다:
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']);
// falseexactly {.collection-method}
exactly 메서드는 주어진 문자열이 다른 문자열과 정확히 일치하는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('Laravel')->exactly('Laravel');
// trueexcerpt {.collection-method}
excerpt 메서드는 문자열 내에서 특정 구문이 처음 등장하는 위치와 일치하는 발췌문을 추출합니다:
use Illuminate\Support\Str;
$excerpt = Str::of('This is my name')->excerpt('my', [
'radius' => 3
]);
// '...is my na...'radius 옵션은 기본값이 100이며, 잘라낸 문자열의 양쪽에 표시되어야 하는 문자 수를 정의할 수 있습니다.
또한, omission 옵션을 사용하여 잘라낸 문자열의 앞뒤에 추가될 문자열을 변경할 수 있습니다:
use Illuminate\Support\Str;
$excerpt = Str::of('This is my name')->excerpt('name', [
'radius' => 3,
'omission' => '(...) '
]);
// '(...) my name'explode {.collection-method}
explode 메서드는 주어진 구분자로 문자열을 나누고, 나뉜 문자열의 각 부분을 담은 컬렉션을 반환합니다:
use Illuminate\Support\Str;
$collection = Str::of('foo bar baz')->explode(' ');
// collect(['foo', 'bar', 'baz'])finish {.collection-method}
finish 메서드는 문자열이 주어진 값으로 끝나지 않는 경우 해당 값을 한 번 추가합니다:
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->finish('/');
// this/string/
$adjusted = Str::of('this/string/')->finish('/');
// this/string/fromBase64 {.collection-method}
fromBase64 메서드는 주어진 Base64 문자열을 디코딩합니다:
use Illuminate\Support\Str;
$decoded = Str::of('TGFyYXZlbA==')->fromBase64();
// Laravelhash {.collection-method}
hash 메서드는 주어진 알고리즘을 사용하여 문자열을 해시합니다:
use Illuminate\Support\Str;
$hashed = Str::of('secret')->hash(algorithm: 'sha256');
// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'headline {.collection-method}
headline 메서드는 대소문자, 하이픈, 또는 언더스코어로 구분된 문자열을 각 단어의 첫 글자가 대문자인 공백으로 구분된 문자열로 변환합니다:
use Illuminate\Support\Str;
$headline = Str::of('taylor_otwell')->headline();
// Taylor Otwell
$headline = Str::of('EmailNotificationSent')->headline();
// Email Notification Sentinitials {.collection-method}
initials 메서드는 문자열을 그 이니셜로 변환합니다:
use Illuminate\Support\Str;
$initials = Str::of('Taylor Otwell')->initials()->upper();
// TOinlineMarkdown {.collection-method}
inlineMarkdown 메서드는 CommonMark를 사용하여 GitHub 플레이버 Markdown을 인라인 HTML로 변환합니다. 그러나 markdown 메서드와 달리, 생성된 모든 HTML을 블록 레벨 엘리먼트로 감싸지 않습니다:
use Illuminate\Support\Str;
$html = Str::of('**Laravel**')->inlineMarkdown();
// <strong>Laravel</strong>Markdown 보안
기본적으로 Markdown은 원시 HTML을 지원하는데, 이는 원시 사용자 입력과 함께 사용할 경우 크로스 사이트 스크립팅(XSS) 취약점을 노출시킬 수 있습니다. CommonMark 보안 문서에 따르면, html_input 옵션을 사용하여 원시 HTML을 이스케이프하거나 제거할 수 있으며, allow_unsafe_links 옵션을 사용하여 안전하지 않은 링크를 허용할지 여부를 지정할 수 있습니다. 일부 원시 HTML을 허용해야 하는 경우, 컴파일된 Markdown을 HTML Purifier를 통해 전달해야 합니다:
use Illuminate\Support\Str;
Str::of('Inject: <script>alert("Hello XSS!");</script>')->inlineMarkdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// Inject: alert("Hello XSS!");is {.collection-method}
is 메서드는 주어진 문자열이 주어진 패턴과 일치하는지 확인합니다. 별표는 와일드카드 값으로 사용할 수 있습니다
use Illuminate\Support\Str;
$matches = Str::of('foobar')->is('foo*');
// true
$matches = Str::of('foobar')->is('baz*');
// falseisAscii {.collection-method}
isAscii 메서드는 주어진 문자열이 ASCII 문자열인지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('Taylor')->isAscii();
// true
$result = Str::of('ü')->isAscii();
// falseisEmpty {.collection-method}
isEmpty 메서드는 주어진 문자열이 비어 있는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of(' ')->trim()->isEmpty();
// true
$result = Str::of('Laravel')->trim()->isEmpty();
// falseisNotEmpty {.collection-method}
isNotEmpty 메서드는 주어진 문자열이 비어 있지 않은지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of(' ')->trim()->isNotEmpty();
// false
$result = Str::of('Laravel')->trim()->isNotEmpty();
// trueisJson {.collection-method}
isJson 메서드는 주어진 문자열이 유효한 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();
// falseisUlid {.collection-method}
isUlid 메서드는 주어진 문자열이 ULID인지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
// true
$result = Str::of('Taylor')->isUlid();
// falseisUrl {.collection-method}
isUrl 메서드는 주어진 문자열이 URL인지 판단합니다:
use Illuminate\Support\Str;
$result = Str::of('http://example.com')->isUrl();
// true
$result = Str::of('Taylor')->isUrl();
// falseisUrl 메서드는 다양한 범위의 프로토콜을 유효한 것으로 간주합니다. 하지만 isUrl 메서드에 유효한 것으로 간주할 프로토콜을 지정하여 전달할 수 있습니다:
$result = Str::of('http://example.com')->isUrl(['http', 'https']);isUuid {.collection-method}
isUuid 메서드는 주어진 문자열이 UUID인지 판단합니다:
use Illuminate\Support\Str;
$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
// true
$result = Str::of('Taylor')->isUuid();
// false주어진 UUID가 버전(1, 3, 4, 5, 6, 7 또는 8)에 따른 UUID 사양과 일치하는지도 검증할 수 있습니다:
use Illuminate\Support\Str;
$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4);
// true
$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1);
// falsekebab {.collection-method}
kebab 메서드는 주어진 문자열을 kebab-case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->kebab();
// foo-barlcfirst {.collection-method}
lcfirst 메서드는 주어진 문자열의 첫 번째 문자를 소문자로 변경하여 반환합니다:
use Illuminate\Support\Str;
$string = Str::of('Foo Bar')->lcfirst();
// foo Barlength {.collection-method}
length 메서드는 주어진 문자열의 길이를 반환합니다:
use Illuminate\Support\Str;
$length = Str::of('Laravel')->length();
// 7limit {.collection-method}
limit 메서드는 주어진 문자열을 지정된 길이로 자릅니다:
use Illuminate\Support\Str;
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox...두 번째 인수를 전달하여 잘린 문자열의 끝에 추가될 문자열을 변경할 수도 있습니다:
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)문자열을 자를 때 완전한 단어를 보존하고 싶다면 preserveWords 인수를 사용할 수 있습니다. 이 인수가 true이면 문자열은 가장 가까운 완전한 단어 경계까지 잘립니다:
$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true);
// The quick...lower {.collection-method}
lower 메서드는 주어진 문자열을 소문자로 변환합니다:
use Illuminate\Support\Str;
$result = Str::of('LARAVEL')->lower();
// 'laravel'markdown {.collection-method}
markdown 메서드는 GitHub 방식의 Markdown을 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>Markdown 보안
기본적으로 Markdown은 원시 HTML을 지원하므로, 사용자 입력을 그대로 사용할 경우 크로스 사이트 스크립팅(XSS) 취약점이 발생할 수 있습니다. CommonMark 보안 문서에 따라, html_input 옵션을 사용하여 원시 HTML을 이스케이프하거나 제거할 수 있으며, allow_unsafe_links 옵션으로 안전하지 않은 링크의 허용 여부를 지정할 수 있습니다. 만약 일부 원시 HTML을 허용해야 한다면, 컴파일된 Markdown을 HTML Purifier를 통해 처리해야 합니다:
use Illuminate\Support\Str;
Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// <p>Inject: alert("Hello XSS!");</p>mask {.collection-method}
mask 메서드는 문자열의 일부를 반복되는 문자로 마스킹하며, 이메일 주소나 전화번호와 같은 문자열의 일부를 가리는 데 사용할 수 있습니다:
use Illuminate\Support\Str;
$string = Str::of('taylor@example.com')->mask('*', 3);
// tay***************mask 메서드의 세 번째나 네 번째 인수로 음수를 전달할 수도 있는데, 이 경우 메서드는 문자열 끝에서부터 지정된 거리만큼 떨어진 곳에서 마스킹을 시작하도록 지시받습니다:
$string = Str::of('taylor@example.com')->mask('*', -15, 3);
// tay***@example.com
$string = Str::of('taylor@example.com')->mask('*', 4, -4);
// tayl**********.commatch {.collection-method}
match 메서드는 주어진 정규식 패턴과 일치하는 문자열의 일부분을 반환합니다:
use Illuminate\Support\Str;
$result = Str::of('foo bar')->match('/bar/');
// 'bar'
$result = Str::of('foo bar')->match('/foo (.*)/');
// 'bar'matchAll {.collection-method}
matchAll 메서드는 주어진 정규식 패턴과 일치하는 문자열의 부분들을 담은 컬렉션을 반환합니다:
use Illuminate\Support\Str;
$result = Str::of('bar foo bar')->matchAll('/bar/');
// collect(['bar', 'bar'])표현식 내에 매칭 그룹을 지정하면, Laravel은 첫 번째 매칭 그룹의 일치 항목들로 이루어진 컬렉션을 반환합니다:
use Illuminate\Support\Str;
$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
// collect(['un', 'ly']);일치하는 항목이 없으면 빈 컬렉션이 반환됩니다.
isMatch {.collection-method}
isMatch 메서드는 문자열이 주어진 정규 표현식과 일치하면 true를 반환합니다:
use Illuminate\Support\Str;
$result = Str::of('foo bar')->isMatch('/foo (.*)/');
// true
$result = Str::of('laravel')->isMatch('/foo (.*)/');
// falsenewLine {.collection-method}
newLine 메서드는 문자열에 "줄바꿈" 문자를 추가합니다:
use Illuminate\Support\Str;
$padded = Str::of('Laravel')->newLine()->append('Framework');
// 'Laravel
// Framework'padBoth {.collection-method}
padBoth 메서드는 PHP의 str_pad 함수를 래핑한 것으로, 문자열이 원하는 길이에 도달할 때까지 문자열 양쪽을 다른 문자열로 채웁니다:
use Illuminate\Support\Str;
$padded = Str::of('James')->padBoth(10, '_');
// '__James___'
$padded = Str::of('James')->padBoth(10);
// ' James 'padLeft {.collection-method}
padLeft 메서드는 PHP의 str_pad 함수를 래핑한 것으로, 문자열이 원하는 길이에 도달할 때까지 문자열 왼쪽을 다른 문자열로 채웁니다:
use Illuminate\Support\Str;
$padded = Str::of('James')->padLeft(10, '-=');
// '-=-=-James'
$padded = Str::of('James')->padLeft(10);
// ' James'padRight {.collection-method}
padRight 메서드는 PHP의 str_pad 함수를 감싸며, 문자열의 오른쪽에 다른 문자열을 채워서 최종 문자열이 원하는 길이에 도달할 때까지 채워줍니다:
use Illuminate\Support\Str;
$padded = Str::of('James')->padRight(10, '-');
// 'James-----'
$padded = Str::of('James')->padRight(10);
// 'James 'pipe {.collection-method}
pipe 메서드는 현재 값을 주어진 콜러블(callable)에 전달하여 문자열을 변환할 수 있게 해줍니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');
// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
$closure = Str::of('foo')->pipe(function (Stringable $str) {
return 'bar';
});
// 'bar'counted {.collection-method}
counted 메서드는 단수형 단어 문자열을 주어진 개수에 따라 단수 또는 복수형으로 변환하고, 그 결과 앞에 형식화된 개수를 붙입니다:
use Illuminate\Support\Str;
$label = Str::of('order')->counted(1);
// 1 order
$label = Str::of('order')->counted(1000);
// 1,000 ordersplural {.collection-method}
plural 메서드는 단수형 단어 문자열을 복수형으로 변환합니다. 이 함수는 Laravel의 복수화 기능이 지원하는 모든 언어를 지원합니다:
use Illuminate\Support\Str;
```php
$plural = Str::of('car')->plural();
// cars
$plural = Str::of('child')->plural();
// children정수 인자를 함수에 전달하여 문자열의 단수형 또는 복수형을 가져올 수 있습니다:
use Illuminate\Support\Str;
$plural = Str::of('child')->plural(2);
// children
$plural = Str::of('child')->plural(1);
// childprependCount 인자를 전달하면 포맷된 $count를 복수형 문자열 앞에 붙일 수 있습니다:
use Illuminate\Support\Str;
$label = Str::of('car')->plural(1000, prependCount: true);
// 1,000 carsposition {.collection-method}
position 메서드는 문자열 내에서 부분 문자열이 처음 등장하는 위치를 반환합니다. 부분 문자열이 문자열 내에 존재하지 않으면 false가 반환됩니다:
use Illuminate\Support\Str;
$position = Str::of('Hello, World!')->position('Hello');
// 0
$position = Str::of('Hello, World!')->position('W');
// 7prepend {.collection-method}
prepend 메서드는 주어진 값들을 문자열 앞에 붙입니다:
use Illuminate\Support\Str;
$string = Str::of('Framework')->prepend('Laravel ');
// Laravel Frameworkremove {.collection-method}
remove 메서드는 주어진 값 또는 값의 배열을 문자열에서 제거합니다:
use Illuminate\Support\Str;
```php
$string = Str::of('Arkansas is quite beautiful!')->remove('quite ');
// Arkansas is beautiful!두 번째 매개변수로 false를 전달하면 문자열을 제거할 때 대소문자를 무시하게 할 수 있습니다.
repeat {.collection-method}
repeat 메서드는 주어진 문자열을 반복합니다:
use Illuminate\Support\Str;
$repeated = Str::of('a')->repeat(5);
// aaaaareplace {.collection-method}
replace 메서드는 문자열 내에서 주어진 문자열을 치환합니다:
use Illuminate\Support\Str;
$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');
// Laravel 7.xreplace 메서드는 caseSensitive 인수도 받을 수 있습니다. 기본적으로 replace 메서드는 대소문자를 구분합니다:
$replaced = Str::of('macOS 13.x')->replace(
'macOS', 'iOS', caseSensitive: false
);replaceArray {.collection-method}
replaceArray 메서드는 배열을 사용하여 문자열 내의 주어진 값을 순차적으로 치환합니다:
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:00replaceFirst {.collection-method}
replaceFirst 메서드는 문자열에서 주어진 값이 처음 나타나는 부분을 치환합니다:
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 dogreplaceLast {.collection-method}
replaceLast 메서드는 문자열에서 주어진 값이 마지막으로 등장한 부분을 치환합니다:
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 dogreplaceMatches {.collection-method}
replaceMatches 메서드는 패턴과 일치하는 문자열의 모든 부분을 주어진 치환 문자열로 치환합니다:
use Illuminate\Support\Str;
$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '');
// '15015551000'replaceMatches 메서드는 주어진 패턴과 일치하는 문자열의 각 부분에 대해 호출되는 클로저를 인자로 받을 수도 있으며, 이를 통해 클로저 내부에서 치환 로직을 수행하고 치환된 값을 반환할 수 있습니다:
use Illuminate\Support\Str;
$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
return '['.$matches[0].']';
});
// '[1][2][3]'replaceStart {.collection-method}
replaceStart 메서드는 주어진 값이 문자열의 시작 부분에 나타나는 경우에만 첫 번째로 등장한 부분을 치환합니다:
```php
use Illuminate\Support\Str;
$replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel');
// Laravel World
$replaced = Str::of('Hello World')->replaceStart('World', 'Laravel');
// Hello WorldreplaceEnd {.collection-method}
replaceEnd 메서드는 주어진 값이 문자열의 끝에 나타나는 경우에만 마지막으로 등장하는 값을 대체합니다:
use Illuminate\Support\Str;
$replaced = Str::of('Hello World')->replaceEnd('World', 'Laravel');
// Hello Laravel
$replaced = Str::of('Hello World')->replaceEnd('Hello', 'Laravel');
// Hello Worldscan {.collection-method}
scan 메서드는 sscanf PHP 함수가 지원하는 형식에 따라 문자열로부터 입력을 파싱하여 컬렉션으로 만듭니다:
use Illuminate\Support\Str;
$collection = Str::of('filename.jpg')->scan('%[^.].%s');
// collect(['filename', 'jpg'])singular {.collection-method}
singular 메서드는 문자열을 단수형으로 변환합니다. 이 함수는 라라벨의 pluralizer가 지원하는 모든 언어를 지원합니다:
use Illuminate\Support\Str;
$singular = Str::of('cars')->singular();
// car
$singular = Str::of('children')->singular();
// childslug {.collection-method}
slug 메서드는 주어진 문자열로부터 URL 친화적인 "슬러그"를 생성합니다:
use Illuminate\Support\Str;
$slug = Str::of('Laravel Framework')->slug('-');
// laravel-frameworksnake {.collection-method}
snake 메서드는 주어진 문자열을 snake_case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->snake();
// foo_barsplit {.collection-method}
split 메서드는 정규식을 사용하여 문자열을 컬렉션으로 분할합니다:
use Illuminate\Support\Str;
$segments = Str::of('one, two, three')->split('/[\s,]+/');
// collect(["one", "two", "three"])squish {.collection-method}
squish 메서드는 단어 사이의 불필요한 공백을 포함하여 문자열에서 모든 불필요한 공백을 제거합니다:
use Illuminate\Support\Str;
$string = Str::of(' laravel framework ')->squish();
// laravel frameworkstart {.collection-method}
start 메서드는 문자열이 주어진 값으로 이미 시작하지 않는 경우 해당 값의 단일 인스턴스를 문자열에 추가합니다:
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->start('/');
// /this/string
$adjusted = Str::of('/this/string')->start('/');
// /this/stringstartsWith {.collection-method}
startsWith 메서드는 주어진 문자열이 주어진 값으로 시작하는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->startsWith('This');
// true또한 배열을 전달하여 주어진 문자열이 배열 안의 값들 중 하나로 시작하는지 확인할 수 있습니다:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->startsWith(['This', 'That']);
// truestripTags {.collection-method}
stripTags 메서드는 문자열에서 모든 HTML 및 PHP 태그를 제거합니다:
use Illuminate\Support\Str;
$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags();
// Taylor Otwell
$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags('<b>');
// Taylor <b>Otwell</b>studly {.collection-method}
studly 메서드는 주어진 문자열을 StudlyCase로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->studly();
// FooBarsubstr {.collection-method}
substr 메서드는 주어진 시작 위치와 길이 매개변수로 지정된 문자열의 일부분을 반환합니다:
use Illuminate\Support\Str;
$string = Str::of('Laravel Framework')->substr(8);
// Framework
$string = Str::of('Laravel Framework')->substr(8, 5);
// FramesubstrReplace {.collection-method}
substrReplace 메서드는 두 번째 인수로 지정한 위치부터 시작해서 세 번째 인수로 지정한 문자 개수만큼 문자열의 일부를 대체합니다. 메서드의 세 번째 인수에 0을 전달하면 문자열의 기존 문자를 대체하지 않고 지정된 위치에 문자열을 삽입합니다:
use Illuminate\Support\Str;
$string = Str::of('1300')->substrReplace(':', 2);
// 13:
$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);
// The Laravel Frameworkswap {.collection-method}
swap 메서드는 PHP의 strtr 함수를 사용해 문자열의 여러 값을 대체합니다:
use Illuminate\Support\Str;
$string = Str::of('Tacos are great!')
->swap([
'Tacos' => 'Burritos',
'great' => 'fantastic',
]);
// Burritos are fantastic!take {.collection-method}
take 메서드는 문자열의 시작 부분부터 지정된 개수만큼의 문자를 반환합니다:
use Illuminate\Support\Str;
$taken = Str::of('Build something amazing!')->take(5);
// Buildtap {.collection-method}
tap 메서드는 주어진 클로저에 문자열을 전달하여, 문자열 자체에는 영향을 주지 않으면서 문자열을 확인하고 상호작용할 수 있게 해줍니다. 클로저가 무엇을 반환하든 관계없이 tap 메서드는 원본 문자열을 반환합니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('Laravel')
->append(' Framework')
->tap(function (Stringable $string) {
dump('String after append: '.$string);
})
->upper();
// LARAVEL FRAMEWORKtest {.collection-method}
test 메서드는 문자열이 주어진 정규 표현식 패턴과 일치하는지 확인합니다:
use Illuminate\Support\Str;
$result = Str::of('Laravel Framework')->test('/Laravel/');
// truetitle {.collection-method}
title 메서드는 주어진 문자열을 Title Case로 변환합니다:
use Illuminate\Support\Str;
$converted = Str::of('a nice title uses the correct case')->title();
// A Nice Title Uses The Correct CasetoBase64 {.collection-method}
toBase64 메서드는 주어진 문자열을 Base64로 변환합니다:
use Illuminate\Support\Str;
$base64 = Str::of('Laravel')->toBase64();
// TGFyYXZlbA==toHtmlString {.collection-method}
toHtmlString 메서드는 주어진 문자열을 Illuminate\Support\HtmlString의 인스턴스로 변환하며, 이는 Blade 템플릿에서 렌더링될 때 이스케이프되지 않습니다:
use Illuminate\Support\Str;
$htmlString = Str::of('Nuno Maduro')->toHtmlString();toUri {.collection-method}
toUri 메서드는 주어진 문자열을 Illuminate\Support\Uri의 인스턴스로 변환합니다:
use Illuminate\Support\Str;
$uri = Str::of('https://example.com')->toUri();transliterate {.collection-method}
transliterate 메서드는 주어진 문자열을 가능한 가장 가까운 ASCII 표현으로 변환을 시도합니다:
use Illuminate\Support\Str;
$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate();
// 'test@laravel.com'trim {.collection-method}
trim 메서드는 주어진 문자열을 트림합니다. PHP의 기본 trim 함수와 달리, 라라벨의 trim 메서드는 유니코드 공백 문자도 제거합니다:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->trim();
// 'Laravel'
$string = Str::of('/Laravel/')->trim('/');
// 'Laravel'ltrim {.collection-method}
ltrim 메서드는 문자열의 왼쪽을 트림합니다. PHP의 기본 ltrim 함수와 달리, 라라벨의 ltrim 메서드는 유니코드 공백 문자도 제거합니다:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->ltrim();
// 'Laravel '
$string = Str::of('/Laravel/')->ltrim('/');
// 'Laravel/'rtrim {.collection-method}
rtrim 메서드는 주어진 문자열의 오른쪽을 다듬습니다(trim). PHP의 기본 rtrim 함수와 달리, Laravel의 rtrim 메서드는 유니코드 공백 문자도 제거합니다:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->rtrim();
// ' Laravel'
$string = Str::of('/Laravel/')->rtrim('/');
// '/Laravel'ucfirst {.collection-method}
ucfirst 메서드는 주어진 문자열의 첫 글자를 대문자로 변환하여 반환합니다:
use Illuminate\Support\Str;
$string = Str::of('foo bar')->ucfirst();
// Foo barucsplit {.collection-method}
ucsplit 메서드는 주어진 문자열을 대문자 기준으로 분리하여 컬렉션으로 만듭니다:
use Illuminate\Support\Str;
$string = Str::of('Foo Bar')->ucsplit();
// collect(['Foo ', 'Bar'])ucwords {.collection-method}
ucwords 메서드는 주어진 문자열에서 각 단어의 첫 글자를 대문자로 변환합니다:
use Illuminate\Support\Str;
$string = Str::of('laravel framework')->ucwords();
// Laravel Frameworkunwrap {.collection-method}
unwrap 메서드는 주어진 문자열의 시작과 끝에서 지정된 문자열을 제거합니다:
use Illuminate\Support\Str;
Str::of('-Laravel-')->unwrap('-');
// Laravel
Str::of('{framework: "Laravel"}')->unwrap('{', '}');
// framework: "Laravel"upper {.collection-method}
upper 메서드는 주어진 문자열을 대문자로 변환합니다:
use Illuminate\Support\Str;
$adjusted = Str::of('laravel')->upper();
// LARAVELwhen {.collection-method}
when 메서드는 주어진 조건이 true인 경우 주어진 클로저를 호출합니다. 클로저는 유창한(fluent) 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('Taylor')
->when(true, function (Stringable $string) {
return $string->append(' Otwell');
});
// 'Taylor Otwell'필요한 경우, when 메서드의 세 번째 매개변수로 또 다른 클로저를 전달할 수 있습니다. 이 클로저는 조건 매개변수가 false로 평가될 때 실행됩니다.
whenContains {.collection-method}
whenContains 메서드는 문자열이 주어진 값을 포함하는 경우 주어진 클로저를 호출합니다. 클로저는 유창한(fluent) 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('tony stark')
->whenContains('tony', function (Stringable $string) {
('tony stark')
->whenDoesntEndWith('tony', function (string $string) {
return $string->title();
});
// 'Tony stark'whenDoesntStartWith {.collection-method}
The whenDoesntStartWith method invokes the given closure if the string doesn't start with the given sub-string. The closure will receive the fluent string instance:
use Illuminate\Support\Str;
$string = Str::of('tony stark')
->whenDoesntStartWith('tony', function (string $string) {
return $string->title();
});
// 'Tony stark'whenEmpty {.collection-method}
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(' ')->trim()->whenEmpty(function ($string) {
return $string->trim()->prepend('Laravel');
});
// 'Laravel'whenNotEmpty {.collection-method}
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 {.collection-method}
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 {.collection-method}
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 {.collection-method}
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 {.collection-method}
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 {.collection-method}
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 {.collection-method}
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('laravel')->whenIsAscii(function ($string) {
return $string->title();
});
// 'Laravel'whenIsUlid {.collection-method}
The whenIsUlid method invokes the given closure if the string is a valid ULID. The closure will receive the fluent string instance:
use Illuminate\Support\Str;
$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function ($string) {
return $string->substr(0, 8);
});
// '01gd6r36'whenIsUuid {.collection-method}
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('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function ($string) {
return $string->substr(0, 8);
});
// 'a0a2a2d2'whenTest {.collection-method}
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 {.collection-method}
The wordCount method returns the number of words that a string contains:
use Illuminate\Support\Str;
Str::of('Hello, world!')->wordCount(); // 2words {.collection-method}
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;
Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Perfectly balanced, as >>>use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) {
return $string->title();
});
// 'Disney World'whenDoesntStartWith {.collection-method}
whenDoesntStartWith 메서드는 문자열이 주어진 하위 문자열로 시작하지 않는 경우 주어진 클로저를 호출합니다. 클로저는 유창한(fluent) 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
return $string->title();
});
// 'Disney World'whenEmpty {.collection-method}
whenEmpty 메서드는 문자열이 비어 있는 경우 주어진 클로저를 호출합니다. 클로저가 값을 반환하면 그 값이 whenEmpty 메서드에 의해 반환됩니다. 클로저가 값을 반환하지 않으면 유창한(fluent) 문자열 인스턴스가 반환됩니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of(' ')->trim()->whenEmpty(function (Stringable $string) {
return $string->prepend('Laravel');
});
// 'Laravel'whenNotEmpty {.collection-method}
whenNotEmpty 메서드는 문자열이 비어 있지 않은 경우 주어진 클로저를 호출합니다. 클로저가 값을 반환하면, 그 값이 whenNotEmpty 메서드에 의해 반환됩니다. 클로저가 값을 반환하지 않으면, fluent 문자열 인스턴스가 반환됩니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
return $string->prepend('Laravel ');
});
// 'Laravel Framework'whenStartsWith {.collection-method}
whenStartsWith 메서드는 문자열이 주어진 하위 문자열로 시작하는 경우 주어진 클로저를 호출합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
return $string->title();
});
// 'Disney World'whenEndsWith {.collection-method}
whenEndsWith 메서드는 문자열이 주어진 하위 문자열로 끝나는 경우 주어진 클로저를 호출합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
return $string->title();
});
// 'Disney World'whenExactly {.collection-method}
whenNotExactly {.collection-method}
whenExactly 메서드는 문자열이 주어진 문자열과 정확히 일치할 경우 주어진 클로저를 실행합니다. 클로저는 fluent string 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
return $string->title();
});
// 'Laravel'whenNotExactly {.collection-method}
whenNotExactly 메서드는 문자열이 주어진 문자열과 정확히 일치하지 않을 경우 주어진 클로저를 실행합니다. 클로저는 fluent string 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
return $string->title();
});
// 'Framework'whenIs {.collection-method}
whenIs 메서드는 문자열이 주어진 패턴과 일치할 경우 주어진 클로저를 실행합니다. 별표(*)는 와일드카드 값으로 사용할 수 있습니다. 클로저는 fluent string 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {
return $string->append('/baz');
});
// 'foo/bar/baz'whenIsAscii {.collection-method}
whenIsAscii 메서드는 문자열이 7비트 ASCII일 경우 주어진 클로저를 실행합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
return $string->title();
});
// 'Laravel'whenIsUlid {.collection-method}
whenIsUlid 메서드는 문자열이 유효한 ULID일 경우 주어진 클로저를 실행합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
return $string->substr(0, 8);
});
// '01gd6r36'whenIsUuid {.collection-method}
whenIsUuid 메서드는 문자열이 유효한 UUID일 경우 주어진 클로저를 실행합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
return $string->substr(0, 8);
});
// 'a0a2a2d2'whenTest {.collection-method}
whenTest 메서드는 문자열이 주어진 정규 표현식과 일치할 경우 주어진 클로저를 실행합니다. 클로저는 fluent 문자열 인스턴스를 전달받습니다:
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
return $string->title();
});
// 'Laravel Framework'wordCount {.collection-method}
wordCount 메서드는 문자열에 포함된 단어의 개수를 반환합니다:
use Illuminate\Support\Str;
Str::of('Hello, world!')->wordCount(); // 2words {.collection-method}
words 메서드는 문자열의 단어 개수를 제한합니다. 필요하다면, 잘린 문자열 뒤에 추가할 문자열을 지정할 수 있습니다:
use Illuminate\Support\Str;
$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Perfectly balanced, as >>>wrap {.collection-method}
wrap 메서드는 주어진 문자열을 추가 문자열 또는 한 쌍의 문자열로 감쌉니다:
use Illuminate\Support\Str;
Str::of('Laravel')->wrap('"');
// "Laravel"
Str::is('is')->wrap(before: 'This ', after: ' Laravel!');
// This is Laravel!