본문 바로가기

문자열

업데이트됨

번역일: 2026년 10월 3일

이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.

원문 수정
2026년 10월 3일
번역 갱신
2026년 10월 3일

문자열

소개

Laravel은 문자열을 다루는 다양한 함수를 제공합니다. 프레임워크 내부에서도 사용하며, 애플리케이션에서도 필요에 따라 자유롭게 활용할 수 있습니다.

사용 가능한 메서드

문자열

체이닝 가능한 문자열

문자열

`__()` {.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>'); // &lt;html&gt;foo&lt;/html&gt;

`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'); // 'This is '

`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'); // true

배열을 전달하면 그중 하나라도 포함하는지 확인합니다:

use Illuminate\Support\Str; $contains = Str::contains('This is my name', ['my', 'foo']); // true

ignoreCase를 true로 지정하면 대소문자를 구분하지 않습니다:

use Illuminate\Support\Str; $contains = Str::contains('This is my name', 'MY', ignoreCase: true); // true

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

Str::containsAll은 배열의 값을 모두 포함하는지 확인합니다:

use Illuminate\Support\Str; $containsAll = Str::containsAll('This is my name', ['my', 'name']); // true

ignoreCase를 true로 지정하면 대소문자를 구분하지 않습니다:

use Illuminate\Support\Str; $containsAll = Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true); // true

`Str::doesntContain()` {.collection-method}

Str::doesntContain은 지정한 값이 없는지 확인합니다. 기본적으로 대소문자를 구분합니다:

use Illuminate\Support\Str; $doesntContain = Str::doesntContain('This is name', 'my'); // true

배열을 전달하면 배열의 어떤 값도 포함하지 않는지 확인합니다:

use Illuminate\Support\Str; $doesntContain = Str::doesntContain('This is name', ['my', 'framework']); // true

ignoreCase를 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-Framework

`Str::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

배열을 전달하면 어떤 값으로도 시작하지 않을 때 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'); // 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 스타일 Markdown을 인라인 HTML로 변환합니다. markdown과 달리 결과 전체를 블록 요소로 감싸지 않습니다:

use Illuminate\Support\Str; $html = Str::inlineMarkdown('**Laravel**'); // <strong>Laravel</strong>

Markdown 보안

Markdown은 기본적으로 원시 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(&quot;Hello XSS!&quot;);

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

Str::is는 문자열이 패턴과 일치하는지 확인합니다. 별표를 와일드카드로 사용할 수 있습니다:

use Illuminate\Support\Str; $matches = Str::is('foo*', 'foobar'); // true $matches = Str::is('baz*', 'foobar'); // false

ignoreCase를 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"}'); // false

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

Str::isUrl은 문자열이 유효한 URL인지 확인합니다:

use Illuminate\Support\Str; $isUrl = Str::isUrl('http://example.com'); // true $isUrl = Str::isUrl('laravel'); // false

기본적으로 여러 프로토콜을 허용하며, 인수로 허용할 프로토콜을 제한할 수 있습니다:

$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)을 지정해 해당 버전의 규격에 맞는지도 검증할 수 있습니다:

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::lcfirst는 첫 글자만 소문자로 바꿉니다:

use Illuminate\Support\Str; $string = Str::lcfirst('Foo Bar'); // foo Bar

`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'); // laravel

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

Str::markdown은 CommonMark로 GitHub 스타일 Markdown을 HTML로 변환합니다:

use Illuminate\Support\Str; $html = Str::markdown('# Laravel'); // <h1>Laravel</h1> $html = Str::markdown('# Taylor <b>Otwell</b>', [ 'html_input' => 'strip', ]); // <h1>Taylor Otwell</h1>

Markdown 보안

Markdown은 기본적으로 원시 HTML을 허용하므로 사용자 입력을 그대로 변환하면 XSS 취약점이 생길 수 있습니다. CommonMark 보안 문서에 따라 html_input으로 원시 HTML을 이스케이프하거나 제거하고, allow_unsafe_links로 안전하지 않은 링크 허용 여부를 정할 수 있습니다. 일부 HTML을 허용해야 한다면 변환 결과를 HTML Purifier로 정제하세요:

use Illuminate\Support\Str; Str::markdown('Inject: <script>alert("Hello XSS!");</script>', [ 'html_input' => 'strip', 'allow_unsafe_links' => false, ]); // <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

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

Str::mask는 문자열 일부를 반복 문자로 가립니다. 이메일이나 전화번호 일부를 숨길 때 사용할 수 있습니다:

use Illuminate\Support\Str; $string = Str::mask('taylor@example.com', '*', 3); // tay***************

세 번째 인수에 음수를 전달하면 끝에서 지정한 거리만큼 떨어진 위치부터 가립니다:

$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; $result = Str::isMatch('/foo (.*)/', 'foo bar'); // true $result = Str::isMatch('/foo (.*)/', 'laravel'); // false

`Str::orderedUuid()` {.collection-method}

Str::orderedUuid는 타임스탬프를 앞에 배치한 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}

Str::padRight는 PHP str_pad를 감싸며, 원하는 길이에 도달할 때까지 오른쪽을 채웁니다:

use Illuminate\Support\Str; $padded = Str::padRight('James', 10, '-'); // 'James-----' $padded = Str::padRight('James', 10); // 'James '

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

Str::password는 지정한 길이의 안전한 무작위 비밀번호를 만듭니다. 문자·숫자·기호의 조합이며 기본 길이는 32자입니다:

use Illuminate\Support\Str; $password = Str::password(); // 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4' $password = Str::password(12); // 'qwuar>#V|i]N'

`Str::counted()` {.collection-method}

Str::counted는 개수에 따라 단수·복수형을 선택하고 앞에 서식을 적용한 개수를 붙입니다:

use Illuminate\Support\Str; $label = Str::counted('order', 1); // 1 order $label = Str::counted('order', 1000); // 1,000 orders

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

Str::plural은 단수 단어를 복수형으로 바꿉니다. Laravel 복수형 변환기가 지원하는 언어를 사용할 수 있습니다:

use Illuminate\Support\Str; $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); // child

prependCount를 사용하면 서식이 적용된 $count를 결과 앞에 붙일 수 있습니다:

use Illuminate\Support\Str; $label = Str::plural('car', 1000, prependCount: true); // 1,000 cars

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

Str::pluralStudly는 StudlyCaps 형식의 단수 문자열을 복수형으로 바꿉니다. 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);

테스트에서는 createRandomStringsUsing으로 Str::random의 반환값을 고정할 수 있습니다:

Str::createRandomStringsUsing(function () { return 'fake-random-string'; });

정상적인 무작위 문자열 생성으로 되돌리려면 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.

세 번째 인수를 false로 지정하면 대소문자를 구분하지 않고 제거합니다.

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

Str::repeat는 주어진 문자열을 지정한 횟수만큼 반복합니다:

use Illuminate\Support\Str; $string = 'a'; $repeat = Str::repeat($string, 5); // aaaaa

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

Str::replace는 문자열 안의 지정한 값을 다른 값으로 바꿉니다:

use Illuminate\Support\Str; $string = 'Laravel 11.x'; $replaced = Str::replace('11.x', '12.x', $string); // Laravel 12.x

caseSensitive로 대소문자 구분 여부를 지정할 수 있으며, 기본적으로 구분합니다:

$replaced = Str::replace( 'php', 'Laravel', 'PHP Framework for Web Artisans', caseSensitive: false ); // Laravel Framework for Web Artisans

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

Str::replaceArray는 지정한 값을 배열의 항목으로 순서대로 바꿉니다:

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}

Str::replaceFirst는 처음 나타난 값만 바꿉니다:

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'

클로저를 전달하면 패턴이 일치할 때마다 호출됩니다. 클로저 안에서 교체 값을 계산해 반환할 수 있습니다:

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는 문자열을 단수형으로 바꿉니다. Laravel 복수형 변환기가 지원하는 언어를 사용할 수 있습니다:

use Illuminate\Support\Str; $singular = Str::singular('cars'); // car $singular = Str::singular('children'); // child

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

Str::slug는 URL에 사용하기 적합한 슬러그를 만듭니다:

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

배열을 전달하면 그중 하나로 시작할 때 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는 시작 위치와 길이로 지정한 부분 문자열을 반환합니다:

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과 달리 유니코드 공백도 제거합니다:

use Illuminate\Support\Str; $string = Str::trim(' foo bar '); // 'foo bar'

`Str::ltrim()` {.collection-method}

Str::ltrim은 앞쪽의 공백 또는 지정한 문자를 제거합니다. PHP 기본 ltrim과 달리 유니코드 공백도 제거합니다:

use Illuminate\Support\Str; $string = Str::ltrim(' foo bar '); // 'foo bar '

`Str::rtrim()` {.collection-method}

Str::rtrim은 뒤쪽의 공백 또는 지정한 문자를 제거합니다. PHP 기본 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 인스턴스는 Laravel의 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'); });

정상적인 생성 방식으로 되돌리려면 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는 버전 4 UUID를 생성합니다:

use Illuminate\Support\Str; return (string) Str::uuid();

테스트에서 Str::uuid의 반환값을 고정하려면 createUuidsUsing을 사용합니다:

use Ramsey\Uuid\Uuid; Str::createUuidsUsing(function () { return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9'); });

정상적인 생성 방식으로 되돌리려면 createUuidsNormally를 호출합니다:

Str::createUuidsNormally();

`Str::uuid7()` {.collection-method}

Str::uuid7은 버전 7 UUID를 생성합니다:

use Illuminate\Support\Str; return (string) Str::uuid7();

선택적으로 DateTimeInterface를 전달하면 그 시각을 사용해 시간순 정렬 가능한 UUID를 생성합니다:

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. */

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

Str::words는 단어 수를 제한합니다. 세 번째 인수로 잘린 문자열 끝에 붙일 표시를 지정할 수 있습니다:

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'

인수 없이 호출하면 메서드 호출을 Illuminate\Support\Str로 전달하는 객체를 반환합니다:

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

`trans()` {.collection-method}

trans는 언어 파일에서 지정한 키의 번역을 가져옵니다:

echo trans('messages.welcome');

번역 키가 없으면 키 자체를 반환합니다. 위 예제에서는 messages.welcome이 반환됩니다.

`trans_choice()` {.collection-method}

trans_choice는 개수에 맞는 단수·복수 표현을 선택해 번역합니다:

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

번역 키가 없으면 키 자체를 반환합니다. 위 예제에서는 messages.notifications가 반환됩니다.

체이닝 가능한 문자열

체이닝 가능한 문자열은 문자열 처리를 객체 지향 방식으로 연결하는 인터페이스입니다. 여러 연산을 연속 호출하여 일반적인 문자열 처리보다 읽기 쉽게 작성할 수 있습니다.

`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']); // true

ignoreCase를 true로 지정하면 대소문자를 구분하지 않습니다:

use Illuminate\Support\Str; $contains = Str::of('This is my name')->contains('MY', ignoreCase: true); // true

`containsAll` {.collection-method}

containsAll은 배열의 모든 값을 포함하는지 확인합니다:

use Illuminate\Support\Str; $containsAll = Str::of('This is my name')->containsAll(['my', 'name']); // true

ignoreCase를 true로 지정하면 대소문자를 구분하지 않습니다:

use Illuminate\Support\Str; $containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true); // true

`decrypt` {.collection-method}

decrypt는 암호화된 문자열을 복호화합니다:

use Illuminate\Support\Str; $decrypted = $encrypted->decrypt(); // 'secret'

반대 작업은 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-Framework

`dirname` {.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']); // true

ignoreCase를 true로 지정하면 대소문자를 구분하지 않습니다:

use Illuminate\Support\Str; $doesntContain = Str::of('This is my name')->doesntContain('MY', ignoreCase: true); // false

`doesntEndWith` {.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']); // false

`doesntStartWith` {.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']); // true

`encrypt` {.collection-method}

encrypt는 문자열을 암호화합니다:

use Illuminate\Support\Str; $encrypted = Str::of('secret')->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']); // false

`exactly` {.collection-method}

exactly는 다른 문자열과 정확히 일치하는지 확인합니다:

use Illuminate\Support\Str; $result = Str::of('Laravel')->exactly('Laravel'); // true

`excerpt` {.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(); // Laravel

`hash` {.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 Sent

`initials` {.collection-method}

initials는 각 단어의 첫 글자만 모읍니다:

use Illuminate\Support\Str; $initials = Str::of('Taylor Otwell')->initials()->upper(); // TO

`inlineMarkdown` {.collection-method}

inlineMarkdown은 CommonMark로 GitHub 스타일 Markdown을 인라인 HTML로 변환합니다. markdown과 달리 결과 전체를 블록 요소로 감싸지 않습니다:

use Illuminate\Support\Str; $html = Str::of('**Laravel**')->inlineMarkdown(); // <strong>Laravel</strong>

Markdown 보안

Markdown은 기본적으로 원시 HTML을 허용하므로 사용자 입력을 그대로 변환하면 XSS 취약점이 생길 수 있습니다. CommonMark 보안 문서에 따라 html_input으로 원시 HTML을 이스케이프하거나 제거하고, allow_unsafe_links로 안전하지 않은 링크 허용 여부를 정할 수 있습니다. 일부 HTML을 허용해야 한다면 변환 결과를 HTML Purifier로 정제하세요:

use Illuminate\Support\Str; Str::of('Inject: <script>alert("Hello XSS!");</script>')->inlineMarkdown([ 'html_input' => 'strip', 'allow_unsafe_links' => false, ]); // Inject: alert(&quot;Hello XSS!&quot;);

`is` {.collection-method}

is는 문자열이 패턴과 일치하는지 확인합니다. 별표를 와일드카드로 사용할 수 있습니다:

use Illuminate\Support\Str; $matches = Str::of('foobar')->is('foo*'); // true $matches = Str::of('foobar')->is('baz*'); // false

`isAscii` {.collection-method}

isAscii는 ASCII 문자열인지 확인합니다:

use Illuminate\Support\Str; $result = Str::of('Taylor')->isAscii(); // true $result = Str::of('ü')->isAscii(); // false

`isEmpty` {.collection-method}

isEmpty는 문자열이 비어 있는지 확인합니다:

use Illuminate\Support\Str; $result = Str::of(' ')->trim()->isEmpty(); // true $result = Str::of('Laravel')->trim()->isEmpty(); // false

`isNotEmpty` {.collection-method}

isNotEmpty는 문자열이 비어 있지 않은지 확인합니다:

use Illuminate\Support\Str; $result = Str::of(' ')->trim()->isNotEmpty(); // false $result = Str::of('Laravel')->trim()->isNotEmpty(); // true

`isJson` {.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(); // false

`isUlid` {.collection-method}

isUlid는 유효한 ULID인지 확인합니다:

use Illuminate\Support\Str; $result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid(); // true $result = Str::of('Taylor')->isUlid(); // false

`isUrl` {.collection-method}

isUrl은 유효한 URL인지 확인합니다:

use Illuminate\Support\Str; $result = Str::of('http://example.com')->isUrl(); // true $result = Str::of('Taylor')->isUrl(); // false

기본적으로 여러 프로토콜을 허용하며, 인수로 허용할 프로토콜을 제한할 수 있습니다:

$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

버전(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); // false

`kebab` {.collection-method}

kebab은 문자열을 kebab-case로 변환합니다:

use Illuminate\Support\Str; $converted = Str::of('fooBar')->kebab(); // foo-bar

`lcfirst` {.collection-method}

lcfirst는 첫 글자만 소문자로 바꿉니다:

use Illuminate\Support\Str; $string = Str::of('Foo Bar')->lcfirst(); // foo Bar

`length` {.collection-method}

length는 문자열 길이를 반환합니다:

use Illuminate\Support\Str; $length = Str::of('Laravel')->length(); // 7

`limit` {.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을 허용해야 한다면 변환 결과를 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(&quot;Hello XSS!&quot;);</p>

`mask` {.collection-method}

mask는 문자열 일부를 반복 문자로 가립니다. 이메일이나 전화번호 일부를 숨길 때 사용할 수 있습니다:

use Illuminate\Support\Str; $string = Str::of('taylor@example.com')->mask('*', 3); // tay***************

두 번째 인수인 시작 위치에 음수를 전달하면 문자열 끝에서부터 위치를 계산합니다. 세 번째 인수인 길이가 음수이면 끝에서 그만큼의 문자를 남기고 가립니다:

$string = Str::of('taylor@example.com')->mask('*', -15, 3); // tay***@example.com $string = Str::of('taylor@example.com')->mask('*', 4, -4); // tayl**********.com

`match` {.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'])

캡처 그룹이 있으면 첫 번째 그룹의 일치 결과를 컬렉션으로 반환합니다:

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 (.*)/'); // false

`newLine` {.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 orders

`plural` {.collection-method}

plural은 단수 단어를 복수형으로 바꿉니다. Laravel 복수형 변환기가 지원하는 언어를 사용할 수 있습니다:

use Illuminate\Support\Str; $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); // child

prependCount로 서식을 적용한 $count를 앞에 붙일 수 있습니다:

use Illuminate\Support\Str; $label = Str::of('car')->plural(1000, prependCount: true); // 1,000 cars

`position` {.collection-method}

position은 부분 문자열이 처음 나타나는 위치를 반환합니다. 없으면 false를 반환합니다:

use Illuminate\Support\Str; $position = Str::of('Hello, World!')->position('Hello'); // 0 $position = Str::of('Hello, World!')->position('W'); // 7

`prepend` {.collection-method}

prepend는 지정한 값들을 문자열 앞에 붙입니다:

use Illuminate\Support\Str; $string = Str::of('Framework')->prepend('Laravel '); // Laravel Framework

`remove` {.collection-method}

remove는 지정한 값 또는 값 배열에 해당하는 부분을 제거합니다:

use Illuminate\Support\Str; $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); // aaaaa

`replace` {.collection-method}

replace는 문자열 안의 지정한 값을 교체합니다:

use Illuminate\Support\Str; $replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x'); // Laravel 7.x

caseSensitive로 대소문자 구분 여부를 지정하며 기본적으로 구분합니다:

$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:00

`replaceFirst` {.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 dog

`replaceLast` {.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 dog

`replaceMatches` {.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는 지정한 값이 맨 앞에 있을 때만 해당 접두사를 바꿉니다:

use Illuminate\Support\Str; $replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel'); // Laravel World $replaced = Str::of('Hello World')->replaceStart('World', 'Laravel'); // Hello World

`replaceEnd` {.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 World

`scan` {.collection-method}

scan은 PHP sscanf가 지원하는 형식으로 문자열을 파싱해 컬렉션으로 반환합니다:

use Illuminate\Support\Str; $collection = Str::of('filename.jpg')->scan('%[^.].%s'); // collect(['filename', 'jpg'])

`singular` {.collection-method}

singular는 문자열을 단수형으로 바꿉니다. Laravel 복수형 변환기가 지원하는 언어를 사용할 수 있습니다:

use Illuminate\Support\Str; $singular = Str::of('cars')->singular(); // car $singular = Str::of('children')->singular(); // child

`slug` {.collection-method}

slug는 URL에 적합한 슬러그를 만듭니다:

use Illuminate\Support\Str; $slug = Str::of('Laravel Framework')->slug('-'); // laravel-framework

`snake` {.collection-method}

snake는 문자열을 snake_case로 변환합니다:

use Illuminate\Support\Str; $converted = Str::of('fooBar')->snake(); // foo_bar

`split` {.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 framework

`start` {.collection-method}

start는 문자열이 지정한 값으로 시작하지 않으면 앞에 하나를 붙입니다:

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

`startsWith` {.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']); // true

`stripTags` {.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(); // FooBar

`substr` {.collection-method}

substr는 시작 위치와 길이로 지정한 부분 문자열을 반환합니다:

use Illuminate\Support\Str; $string = Str::of('Laravel Framework')->substr(8); // Framework $string = Str::of('Laravel Framework')->substr(8, 5); // Frame

`substrReplace` {.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 Framework

`swap` {.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); // Build

`tap` {.collection-method}

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 FRAMEWORK

`test` {.collection-method}

test는 문자열이 정규식 패턴과 일치하는지 확인합니다:

use Illuminate\Support\Str; $result = Str::of('Laravel Framework')->test('/Laravel/'); // true

`title` {.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 Case

`toBase64` {.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과 달리 유니코드 공백도 제거합니다:

use Illuminate\Support\Str; $string = Str::of(' Laravel ')->trim(); // 'Laravel' $string = Str::of('/Laravel/')->trim('/'); // 'Laravel'

`ltrim` {.collection-method}

ltrim은 앞쪽의 공백이나 지정한 문자를 제거합니다. PHP 기본 ltrim과 달리 유니코드 공백도 제거합니다:

use Illuminate\Support\Str; $string = Str::of(' Laravel ')->ltrim(); // 'Laravel ' $string = Str::of('/Laravel/')->ltrim('/'); // 'Laravel/'

`rtrim` {.collection-method}

rtrim은 뒤쪽의 공백이나 지정한 문자를 제거합니다. PHP 기본 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 bar

`ucsplit` {.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 Framework

`unwrap` {.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(); // LARAVEL

`when` {.collection-method}

when은 조건이 참이면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

use Illuminate\Support\Str; use Illuminate\Support\Stringable; $string = Str::of('Taylor') ->when(true, function (Stringable $string) { return $string->append(' Otwell'); }); // 'Taylor Otwell'

세 번째 인수로 다른 클로저를 전달하면 조건이 거짓일 때 실행됩니다.

`whenContains` {.collection-method}

whenContains는 지정한 값을 포함하면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

use Illuminate\Support\Str; use Illuminate\Support\Stringable; $string = Str::of('tony stark') ->whenContains('tony', function (Stringable $string) { return $string->title(); }); // 'Tony Stark'

세 번째 인수로 다른 클로저를 전달하면 지정한 값을 포함하지 않을 때 실행됩니다.

배열을 전달하면 그중 하나라도 포함하는 경우 실행합니다:

use Illuminate\Support\Str; use Illuminate\Support\Stringable; $string = Str::of('tony stark') ->whenContains(['tony', 'hulk'], function (Stringable $string) { return $string->title(); }); // Tony Stark

`whenContainsAll` {.collection-method}

whenContainsAll은 지정한 부분 문자열을 모두 포함하면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

use Illuminate\Support\Str; use Illuminate\Support\Stringable; $string = Str::of('tony stark') ->whenContainsAll(['tony', 'stark'], function (Stringable $string) { return $string->title(); }); // 'Tony Stark'

세 번째 인수로 다른 클로저를 전달하면 조건을 만족하지 않을 때 실행됩니다.

`whenDoesntEndWith` {.collection-method}

whenDoesntEndWith는 지정한 부분 문자열로 끝나지 않으면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

use Illuminate\Support\Str; use Illuminate\Support\Stringable; $string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) { return $string->title(); }); // 'Disney World'

`whenDoesntStartWith` {.collection-method}

whenDoesntStartWith는 지정한 부분 문자열로 시작하지 않으면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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는 문자열이 비어 있으면 클로저를 호출합니다. 클로저가 값을 반환하면 그 값을 반환하고, 반환값이 없으면 현재 문자열 인스턴스를 반환합니다:

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는 문자열이 비어 있지 않으면 클로저를 호출합니다. 클로저가 값을 반환하면 그 값을 반환하고, 반환값이 없으면 현재 문자열 인스턴스를 반환합니다:

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는 지정한 부분 문자열로 시작하면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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는 지정한 부분 문자열로 끝나면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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}

whenExactly는 지정한 문자열과 정확히 일치하면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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는 지정한 문자열과 정확히 일치하지 않으면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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는 패턴과 일치하면 클로저를 호출합니다. 별표를 와일드카드로 사용할 수 있으며, 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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 문자열이면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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이면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

use Illuminate\Support\Str; $string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) { return $string->substr(0, 8); }); // '01gd6r36'

`whenIsUuid` {.collection-method}

whenIsUuid는 유효한 UUID이면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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는 정규식과 일치하면 클로저를 호출합니다. 클로저에는 현재 문자열 인스턴스가 전달됩니다:

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(); // 2

`words` {.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::of('is')->wrap(before: 'This ', after: ' Laravel!'); // This is Laravel!

이 문서는 Laravel 공식 문서(MIT)를 한국 개발자를 위해 번역·재구성한 것입니다.

번역일: 2026년 10월 3일