文字列
イントロダクション
Laravelは、文字列値を操作するためのさまざまな関数を用意しています。これらの関数の多くはフレームワーク自体が使用していますが、便利であればアプリケーションで自由に使用できます。
利用可能なメソッド
文字列
__ 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::doesntContain Str::deduplicate Str::endsWith Str::excerpt Str::finish 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::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
Fluent文字列
after afterLast apa append ascii basename before beforeLast between betweenFirst camel charAt classBasename chopStart chopEnd contains containsAll deduplicate dirname endsWith exactly excerpt explode finish 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 transliterate trim ltrim rtrim ucfirst ucsplit unwrap upper when whenContains whenContainsAll whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words wrap
文字列
__()
__関数は、言語ファイルを使用して、指定した翻訳文字列または翻訳キーを翻訳します。
1echo __('Welcome to our application');2 3echo __('messages.welcome');
指定した翻訳文字列またはキーが存在しない場合、__関数は指定値を返します。したがって、上記の例を使用すると、翻訳キーが存在しない場合、__関数はmessages.welcomeを返します。
class_basename()
class_basename関数は、指定したクラスの名前から名前空間を削除したクラス名を返します。
1$class = class_basename('Foo\Bar\Baz');2 3// Baz
e()
e関数はPHPのhtmlspecialchars関数を実行しますが、double_encodeオプションはデフォルトでtrueに設定されています。
1echo e('<html>foo</html>');2 3// <html>foo</html>
preg_replace_array()
preg_replace_array関数は、配列を使用して、文字列内の指定パターンを順番に置換します。
1$string = 'The event will take place between :start and :end';2 3$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);4 5// The event will take place between 8:30 and 9:00
Str::after()
Str::afterメソッドは、文字列内の指定値より後のすべてを返します。文字列内に値が存在しない場合は、文字列全体が返されます。
1use Illuminate\Support\Str;2 3$slice = Str::after('This is my name', 'This is');4 5// ' my name'
Str::afterLast()
Str::afterLastメソッドは、文字列内で最後に出現した指定値より後のすべてを返します。文字列内に値が存在しない場合は、文字列全体が返されます。
1use Illuminate\Support\Str;2 3$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');4 5// 'Controller'
Str::apa()
Str::apaメソッドは、APAガイドラインに従い、指定文字列をタイトルケースに変換します。
1use Illuminate\Support\Str;2 3$title = Str::apa('Creating A Project');4 5// 'Creating a Project'
Str::ascii()
Str::asciiメソッドは、文字列をASCII値に音訳しようと試みます。
1use Illuminate\Support\Str;2 3$slice = Str::ascii('û');4 5// 'u'
Str::before()
Str::beforeメソッドは、文字列内の指定値より前のすべてを返します。
1use Illuminate\Support\Str;2 3$slice = Str::before('This is my name', 'my name');4 5// 'This is '
Str::beforeLast()
Str::beforeLastメソッドは、文字列内で最後に出現した指定値より前のすべてを返します。
1use Illuminate\Support\Str;2 3$slice = Str::beforeLast('This is my name', 'is');4 5// 'This '
Str::between()
Str::betweenメソッドは、2つの値に挟まれた文字列の部分を返します。
1use Illuminate\Support\Str;2 3$slice = Str::between('This is my name', 'This', 'name');4 5// ' is my '
Str::betweenFirst()
Str::betweenFirstメソッドは、2つの値に挟まれた文字列のうち、最短の部分を返します。
1use Illuminate\Support\Str;2 3$slice = Str::betweenFirst('[a] bc [d]', '[', ']');4 5// 'a'
Str::camel()
Str::camelメソッドは、指定した文字列をcamelCaseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::camel('foo_bar');4 5// 'fooBar'
Str::charAt()
Str::charAtメソッドは、指定したインデックスの文字を返します。インデックスが範囲外の場合はfalseを返します。
1use Illuminate\Support\Str;2 3$character = Str::charAt('This is my name.', 6);4 5// 's'
Str::chopStart()
Str::chopStartメソッドは、指定値が文字列の先頭にある場合にのみ、その値の最初の出現箇所を削除します。
1use Illuminate\Support\Str;2 3$url = Str::chopStart('https://laravel.dokyumento.jp', 'https://');4 5// 'laravel.com'
第2引数に配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値が文字列から削除されます。
1use Illuminate\Support\Str;2 3$url = Str::chopStart('https://laravel.dokyumento.jp', ['https://', 'http://']);4 5// 'laravel.com'
Str::chopEnd()
Str::chopEndメソッドは、指定値が文字列の末尾にある場合にのみ、その値の最後の出現箇所を削除します。
1use Illuminate\Support\Str;2 3$url = Str::chopEnd('app/Models/Photograph.php', '.php');4 5// 'app/Models/Photograph'
第2引数に配列を渡すこともできます。文字列が配列内のいずれかの値で終わる場合、その値が文字列から削除されます。
1use Illuminate\Support\Str;2 3$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);4 5// 'laravel.com'
Str::contains()
Str::containsメソッドは、指定した文字列に指定値が含まれているかを判定します。デフォルトでこのメソッドは大文字と小文字を区別します。
1use Illuminate\Support\Str;2 3$contains = Str::contains('This is my name', 'my');4 5// true
値の配列を渡して、指定文字列が配列内のいずれかの値を含んでいるかどうかを判断することもできます。
1use Illuminate\Support\Str;2 3$contains = Str::contains('This is my name', ['my', 'foo']);4 5// true
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$contains = Str::contains('This is my name', 'MY', ignoreCase: true);4 5// true
Str::containsAll()
Str::containsAllメソッドは、指定した文字列が、指定した配列内のすべての値を含んでいるかどうかを判定します。
1use Illuminate\Support\Str;2 3$containsAll = Str::containsAll('This is my name', ['my', 'name']);4 5// true
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$containsAll = Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true);4 5// true
Str::doesntContain()
Str::doesntContainメソッドは、指定した文字列が指定値を含んでいないかを判定します。デフォルトでこのメソッドは大文字と小文字を区別します。
1use Illuminate\Support\Str;2 3$doesntContain = Str::doesntContain('This is name', 'my');4 5// true
値の配列を渡して、指定した文字列が配列内のいずれかの値を含んでいないかを判断することもできます。
1use Illuminate\Support\Str;2 3$doesntContain = Str::doesntContain('This is name', ['my', 'foo']);4 5// true
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true);4 5// true
Str::deduplicate()
Str::deduplicateメソッドは、指定した文字列内で連続する文字のインスタンスを1つのインスタンスに置き換えます。デフォルトでは、このメソッドはスペースの重複を削除します。
1use Illuminate\Support\Str;2 3$result = Str::deduplicate('The Laravel Framework');4 5// The Laravel Framework
メソッドの第2引数として渡すことで、重複を削除する別の文字を指定できます。
1use Illuminate\Support\Str;2 3$result = Str::deduplicate('The---Laravel---Framework', '-');4 5// The-Laravel-Framework
Str::endsWith()
Str::endsWithメソッドは、指定した文字列が指定値で終わるか判定します。
1use Illuminate\Support\Str;2 3$result = Str::endsWith('This is my name', 'name');4 5// true
値の配列を渡して、指定した文字列が配列内のいずれかの値で終わるかどうかを判断することもできます。
1use Illuminate\Support\Str;2 3$result = Str::endsWith('This is my name', ['name', 'foo']);4 5// true6 7$result = Str::endsWith('This is my name', ['this', 'foo']);8 9// false
Str::excerpt()
Str::excerptメソッドは、文字列内で最初に見つかったフレーズに一致する部分を、指定した文字列から抜粋します。
1use Illuminate\Support\Str;2 3$excerpt = Str::excerpt('This is my name', 'my', [4 'radius' => 35]);6 7// '...is my na...'
radiusオプション(デフォルトは100)で、切り詰めた文字列の両側に表示する文字数を定義できます。
さらに、omissionオプションを使用して、切り詰めた文字列の前後に付加する文字列を定義できます。
1use Illuminate\Support\Str;2 3$excerpt = Str::excerpt('This is my name', 'name', [4 'radius' => 3,5 'omission' => '(...) '6]);7 8// '(...) my name'
Str::finish()
Str::finishメソッドは、文字列がまだその値で終わっていない場合に、指定した値のインスタンスを1つ追加します。
1use Illuminate\Support\Str;2 3$adjusted = Str::finish('this/string', '/');4 5// this/string/6 7$adjusted = Str::finish('this/string/', '/');8 9// this/string/
Str::headline()
Str::headlineメソッドは、大文字小文字の区切り、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字を大文字にしたスペース区切りの文字列に変換します。
1use Illuminate\Support\Str;2 3$headline = Str::headline('steve_jobs');4 5// Steve Jobs6 7$headline = Str::headline('EmailNotificationSent');8 9// Email Notification Sent
Str::inlineMarkdown()
Str::inlineMarkdownメソッドは、CommonMarkを使用して、GitHubフレーバーのMarkdownをインラインHTMLに変換します。ただし、markdownメソッドとは異なり、生成されたすべてのHTMLをブロックレベル要素でラップしません。
1use Illuminate\Support\Str;2 3$html = Str::inlineMarkdown('**Laravel**');4 5// <strong>Laravel</strong>
Markdownのセキュリティ
CommonMark Securityのドキュメントにあるように、デフォルトでMarkdownは生のHTMLをサポートしており、ユーザーの生の入力と合わせて使用するとクロスサイトスクリプティング(XSS)の脆弱性を引き起こします。html_inputオプションを使用して生のHTMLをエスケープまたは除去したり、allow_unsafe_linksオプションで安全でないリンクを許可するかを指定したりできます。生のHTMLの一部を許可する必要がある場合は、コンパイルしたMarkdownをHTML Purifierに通す必要があります。
1use Illuminate\Support\Str;2 3Str::inlineMarkdown('Inject: <script>alert("Hello XSS!");</script>', [4 'html_input' => 'strip',5 'allow_unsafe_links' => false,6]);7 8// Inject: alert("Hello XSS!");
Str::is()
Str::isメソッドは、指定した文字列が指定したパターンに一致するかどうかを判定します。アスタリスクはワイルドカードとして使用できます。
1use Illuminate\Support\Str;2 3$matches = Str::is('foo*', 'foobar');4 5// true6 7$matches = Str::is('baz*', 'foobar');8 9// false
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$matches = Str::is('*.jpg', 'photo.JPG', ignoreCase: true);4 5// true
Str::isAscii()
Str::isAsciiメソッドは、指定した文字列が7ビットASCIIであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$isAscii = Str::isAscii('Taylor');4 5// true6 7$isAscii = Str::isAscii('ü');8 9// false
Str::isJson()
Str::isJsonメソッドは、指定した文字列が有効なJSONであるかどうかを判定します。
1use Illuminate\Support\Str; 2 3$result = Str::isJson('[1,2,3]'); 4 5// true 6 7$result = Str::isJson('{"first": "John", "last": "Doe"}'); 8 9// true10 11$result = Str::isJson('{first: "John", last: "Doe"}');12 13// false
Str::isUrl()
Str::isUrlメソッドは、指定した文字列が有効なURLであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$isUrl = Str::isUrl('http://example.com');4 5// true6 7$isUrl = Str::isUrl('laravel');8 9// false
isUrlメソッドは、幅広いプロトコルを有効とみなします。しかし、isUrlメソッドにプロトコルを指定することで、有効とみなすプロトコルを指定できます。
1$isUrl = Str::isUrl('http://example.com', ['http', 'https']);
Str::isUlid()
Str::isUlidメソッドは、指定した文字列が有効なULIDであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');4 5// true6 7$isUlid = Str::isUlid('laravel');8 9// false
Str::isUuid()
Str::isUuidメソッドは、指定した文字列が有効なUUIDであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');4 5// true6 7$isUuid = Str::isUuid('laravel');8 9// false
Str::kebab()
Str::kebabメソッドは、指定した文字列をkebab-caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::kebab('fooBar');4 5// foo-bar
Str::lcfirst()
Str::lcfirstメソッドは、指定した文字列の最初の文字を小文字にして返します。
1use Illuminate\Support\Str;2 3$string = Str::lcfirst('Foo Bar');4 5// foo Bar
Str::length()
Str::lengthメソッドは、指定した文字列の長さを返します。
1use Illuminate\Support\Str;2 3$length = Str::length('Laravel');4 5// 7
Str::limit()
Str::limitメソッドは、指定した文字列を指定した長さに切り詰めます。
1use Illuminate\Support\Str;2 3$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);4 5// The quick brown fox...
メソッドに第3引数を渡し、切り詰めた文字列の末尾に追加する文字列を変更できます。
1$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');2 3// The quick brown fox (...)
文字列を切り詰める際に単語を完全に残したい場合は、preserveWords引数が利用できます。この引数がtrueの場合、文字列は最も近い完全な単語の境界で切り詰められます。
1$truncated = Str::limit('The quick brown fox', 12, preserveWords: true);2 3// The quick...
Str::lower()
Str::lowerメソッドは、指定した文字列を小文字に変換します。
1use Illuminate\Support\Str;2 3$converted = Str::lower('LARAVEL');4 5// laravel
Str::markdown()
Str::markdownメソッドは、CommonMarkを使用して、GitHubフレーバーのMarkdownをHTMLに変換します。
1use Illuminate\Support\Str; 2 3$html = Str::markdown('# Laravel'); 4 5// <h1>Laravel</h1> 6 7$html = Str::markdown('# Taylor <b>Otwell</b>', [ 8 'html_input' => 'strip', 9]);10 11// <h1>Taylor Otwell</h1>
Markdownのセキュリティ
CommonMark Securityのドキュメントにあるように、デフォルトでMarkdownは生のHTMLをサポートしており、ユーザーの生の入力と合わせて使用するとクロスサイトスクリプティング(XSS)の脆弱性を引き起こします。html_inputオプションを使用して生のHTMLをエスケープまたは除去したり、allow_unsafe_linksオプションで安全でないリンクを許可するかを指定したりできます。生のHTMLの一部を許可する必要がある場合は、コンパイルしたMarkdownをHTML Purifierに通す必要があります。
1use Illuminate\Support\Str;2 3Str::markdown('Inject: <script>alert("Hello XSS!");</script>', [4 'html_input' => 'strip',5 'allow_unsafe_links' => false,6]);7 8// <p>Inject: alert("Hello XSS!");</p>
Str::mask()
Str::maskメソッドは、文字列の一部を繰り返し文字でマスクし、メールアドレスや電話番号などの文字列の一部を難読化するために使用します。
1use Illuminate\Support\Str;2 4 5// tay***************
必要であれば、maskメソッドの第3引数に負の数を指定できます。これにより、メソッドは文字列の末尾から指定した距離でマスキングを開始します。
2 3// tay***@example.com
Str::orderedUuid()
Str::orderedUuidメソッドは、「タイムスタンプが先頭」のUUIDを生成し、インデックス付きのデータベースカラムに効率的に保存できます。このメソッドを使用して生成された各UUIDは、以前にメソッドを使用して生成されたUUIDの後にソートされます。
1use Illuminate\Support\Str;2 3return (string) Str::orderedUuid();
Str::padBoth()
Str::padBothメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の両側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::padBoth('James', 10, '_');4 5// '__James___'6 7$padded = Str::padBoth('James', 10);8 9// ' James '
Str::padLeft()
Str::padLeftメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の左側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::padLeft('James', 10, '-=');4 5// '-=-=-James'6 7$padded = Str::padLeft('James', 10);8 9// ' James'
Str::padRight()
Str::padRightメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の右側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::padRight('James', 10, '-');4 5// 'James-----'6 7$padded = Str::padRight('James', 10);8 9// 'James '
Str::password()
Str::passwordメソッドは、指定した長さの安全なランダムパスワードを生成するために使用します。パスワードは、文字、数字、記号、スペースの組み合わせで構成されます。デフォルトでは、パスワードは32文字の長さです。
1use Illuminate\Support\Str;2 3$password = Str::password();4 5// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'6 7$password = Str::password(12);8 9// 'qwuar>#V|i]N'
Str::plural()
Str::pluralメソッドは、単数形の単語文字列を複数形に変換します。この関数は、Laravelの複数形変換機能がサポートするすべての言語をサポートしています。
1use Illuminate\Support\Str;2 3$plural = Str::plural('car');4 5// cars6 7$plural = Str::plural('child');8 9// children
関数の第2引数に整数を指定して、文字列の単数形または複数形を取得できます。
1use Illuminate\Support\Str;2 3$plural = Str::plural('child', 2);4 5// children6 7$singular = Str::plural('child', 1);8 9// child
Str::pluralStudly()
Str::pluralStudlyメソッドは、スタディケース形式の単数形単語文字列を複数形に変換します。この関数は、Laravelの複数形変換機能がサポートするすべての言語をサポートしています。
1use Illuminate\Support\Str;2 3$plural = Str::pluralStudly('VerifiedHuman');4 5// VerifiedHumans6 7$plural = Str::pluralStudly('UserFeedback');8 9// UserFeedback
関数の第2引数に整数を指定して、文字列の単数形または複数形を取得できます。
1use Illuminate\Support\Str;2 3$plural = Str::pluralStudly('VerifiedHuman', 2);4 5// VerifiedHumans6 7$singular = Str::pluralStudly('VerifiedHuman', 1);8 9// VerifiedHuman
Str::position()
Str::positionメソッドは、文字列内で部分文字列が最初に出現する位置を返します。部分文字列が指定の文字列内に存在しない場合は、falseが返されます。
1use Illuminate\Support\Str;2 3$position = Str::position('Hello, World!', 'Hello');4 5// 06 7$position = Str::position('Hello, World!', 'W');8 9// 7
Str::random()
Str::randomメソッドは、指定した長さのランダムな文字列を生成します。この関数はPHPのrandom_bytes関数を使用します。
1use Illuminate\Support\Str;2 3$random = Str::random(40);
テスト中、Str::randomメソッドが返す値を「偽装」すると便利な場合があります。これを実現するには、createRandomStringsUsingメソッドを使用します。
1Str::createRandomStringsUsing(function () {2 return 'fake-random-string';3});
randomメソッドに通常のランダムな文字列の生成に戻すように指示するには、createRandomStringsNormallyメソッドを呼び出します。
1Str::createRandomStringsNormally();
Str::remove()
Str::removeメソッドは、指定した値または値の配列を文字列から削除します。
1use Illuminate\Support\Str;2 3$string = 'Peter Piper picked a peck of pickled peppers.';4 5$removed = Str::remove('e', $string);6 7// Ptr Pipr pickd a pck of pickld ppprs.
また、removeメソッドの第3引数としてfalseを渡すと、文字列を削除する際に大文字と小文字の区別を無視できます。
Str::repeat()
Str::repeatメソッドは、指定した文字列を繰り返します。
1use Illuminate\Support\Str;2 3$string = 'a';4 5$repeat = Str::repeat($string, 5);6 7// aaaaa
Str::replace()
Str::replaceメソッドは、文字列内の指定した文字列を置き換えます。
1use Illuminate\Support\Str;2 3$string = 'Laravel 10.x';4 5$replaced = Str::replace('10.x', '11.x', $string);6 7// Laravel 11.x
replaceメソッドは、caseSensitive引数も受け入れます。デフォルトでは、replaceメソッドは大文字と小文字を区別します。
1Str::replace('Framework', 'Laravel', caseSensitive: false);
Str::replaceArray()
Str::replaceArrayメソッドは、配列を使用して、文字列内の指定した値を順番に置き換えます。
1use Illuminate\Support\Str;2 3$string = 'The event will take place between ? and ?';4 5$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);6 7// The event will take place between 8:30 and 9:00
Str::replaceFirst()
Str::replaceFirstメソッドは、文字列内で最初に出現した指定値を置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');4 5// a quick brown fox jumps over the lazy dog
Str::replaceLast()
Str::replaceLastメソッドは、文字列内で最後に出現した指定値を置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');4 5// the quick brown fox jumps over a lazy dog
Str::replaceMatches()
Str::replaceMatchesメソッドは、パターンに一致する文字列のすべての部分を指定した置換文字列に置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceMatches(4 pattern: '/[^A-Za-z0-9]++/',5 replace: '',6 subject: '(+1) 501-555-1000'7)8 9// '15015551000'
replaceMatchesメソッドはクロージャも受け入れます。このクロージャは、指定したパターンに一致する文字列の各部分に対して呼び出され、クロージャ内で置換ロジックを実行し、置換された値を返すことができます。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceMatches('/\d/', function (array $matches) {4 return '['.$matches[0].']';5}, '123');6 7// '[1][2][3]'
Str::replaceStart()
Str::replaceStartメソッドは、指定値が文字列の先頭にある場合にのみ、その値の最初の出現箇所を置換します。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');4 5// Laravel World6 7$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');8 9// Hello World
Str::replaceEnd()
Str::replaceEndメソッドは、指定値が文字列の末尾にある場合にのみ、その値の最後の出現箇所を置換します。
1use Illuminate\Support\Str;2 3$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World');4 5// Hello Laravel6 7$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World');8 9// Hello World
Str::reverse()
Str::reverseメソッドは、指定した文字列を反転させます。
1use Illuminate\Support\Str;2 3$reversed = Str::reverse('Hello World');4 5// dlroW olleH
Str::singular()
Str::singularメソッドは、文字列を単数形に変換します。この関数は、Laravelの複数形変換機能がサポートするすべての言語をサポートしています。
1use Illuminate\Support\Str;2 3$singular = Str::singular('cars');4 5// car6 7$singular = Str::singular('children');8 9// child
Str::slug()
Str::slugメソッドは、指定した文字列からURLフレンドリーな「スラグ」を生成します。
1use Illuminate\Support\Str;2 3$slug = Str::slug('Laravel 5 Framework', '-');4 5// laravel-5-framework
Str::snake()
Str::snakeメソッドは、指定した文字列をsnake_caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::snake('fooBar');4 5// foo_bar6 7$converted = Str::snake('fooBar', '-');8 9// foo-bar
Str::squish()
Str::squishメソッドは、単語間の余分な空白を含む、文字列からすべての余分な空白を削除します。
1use Illuminate\Support\Str;2 3$string = Str::squish(' laravel framework ');4 5// laravel framework
Str::start()
Str::startメソッドは、文字列がまだその値で始まっていない場合に、指定した値のインスタンスを1つ追加します。
1use Illuminate\Support\Str;2 3$adjusted = Str::start('this/string', '/');4 5// /this/string6 7$adjusted = Str::start('/this/string', '/');8 9// /this/string
Str::startsWith()
Str::startsWithメソッドは、指定した文字列が指定値で始まるか判定します。
1use Illuminate\Support\Str;2 3$result = Str::startsWith('This is my name', 'This');4 5// true
使用可能な値の配列を渡した場合、startsWithメソッドは、文字列が指定値のいずれかで始まっていれば、trueを返します。
1$result = Str::startsWith('This is my name', ['This', 'That', 'There']);2 3// true
Str::studly()
Str::studlyメソッドは、指定した文字列をStudlyCaseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::studly('foo_bar');4 5// FooBar
Str::substr()
Str::substrメソッドは、開始パラメータと長さパラメータで指定された文字列の一部を返します。
1use Illuminate\Support\Str;2 3$converted = Str::substr('The Laravel Framework', 4, 7);4 5// Laravel
Str::substrCount()
Str::substrCountメソッドは、指定した文字列内で指定した値が出現する回数を返します。
1use Illuminate\Support\Str;2 3$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');4 5// 2
Str::substrReplace()
Str::substrReplaceメソッドは、第3引数で指定された位置から始まり、第4引数で指定された文字数を置き換えることで、文字列の一部分のテキストを置き換えます。メソッドの第4引数に0を渡すと、文字列内の既存の文字を置き換えることなく、指定された位置に文字列を挿入します。
1use Illuminate\Support\Str;2 3$result = Str::substrReplace('1300', ':', 2);4// 13:5 6$result = Str::substrReplace('1300', ':', 2, 0);7// 13:00
Str::swap()
Str::swapメソッドは、PHPのstrtr関数を使用して、指定した文字列内の複数の値を置換します。
1use Illuminate\Support\Str;2 3$string = Str::swap([4 'Tacos' => 'Burritos',5 'great' => 'fantastic',6], 'Tacos are great!');7 8// Burritos are fantastic!
Str::take()
Str::takeメソッドは、文字列の先頭から指定された文字数を返します。
1use Illuminate\Support\Str;2 3$taken = Str::take('Build something amazing!', 5);4 5// Build
Str::title()
Str::titleメソッドは、指定した文字列をTitle Caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::title('a nice title uses the correct case');4 5// A Nice Title Uses The Correct Case
Str::toBase64()
Str::toBase64メソッドは、指定した文字列をBase64に変換します。
1use Illuminate\Support\Str;2 3$base64 = Str::toBase64('Laravel');4 5// TGFyYXZlbA==
Str::transliterate()
Str::transliterateメソッドは、指定した文字列を最も近いASCII表現に変換しようと試みます。
1use Illuminate\Support\Str;2 3$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');4
Str::trim()
Str::trimメソッドは、指定した文字列の先頭と末尾から空白(または他の文字)を取り除きます。PHPネイティブのtrim関数とは異なり、Str::trimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::trim(' foo bar ');4 5// 'foo bar'
Str::ltrim()
Str::ltrimメソッドは、指定した文字列の先頭から空白(または他の文字)を取り除きます。PHPネイティブのltrim関数とは異なり、Str::ltrimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::ltrim(' foo bar ');4 5// 'foo bar '
Str::rtrim()
Str::rtrimメソッドは、指定した文字列の末尾から空白(または他の文字)を取り除きます。PHPネイティブのrtrim関数とは異なり、Str::rtrimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::rtrim(' foo bar ');4 5// ' foo bar'
Str::ucfirst()
Str::ucfirstメソッドは、指定した文字列の最初の文字を大文字にして返します。
1use Illuminate\Support\Str;2 3$string = Str::ucfirst('foo bar');4 5// Foo bar
Str::ucsplit()
Str::ucsplitメソッドは、指定した文字列を大文字で配列に分割します。
1use Illuminate\Support\Str;2 3$segments = Str::ucsplit('FooBar');4 5// [0 => 'Foo', 1 => 'Bar']
Str::upper()
Str::upperメソッドは、指定した文字列を大文字に変換します。
1use Illuminate\Support\Str;2 3$string = Str::upper('laravel');4 5// LARAVEL
Str::ulid()
Str::ulidメソッドは、コンパクトで時間順にソートされる一意な識別子であるULIDを生成します。
1use Illuminate\Support\Str;2 3return (string) Str::ulid();4 5// 01gd6r360bp37zj17nxb55yv40
指定したULIDが作成された日時を表すIlluminate\Support\Carbon日付インスタンスを取得したい場合は、LaravelのCarbon統合が提供するcreateFromIdメソッドを使用できます。
1use Illuminate\Support\Carbon;2use Illuminate\Support\Str;3 4$date = Carbon::createFromId((string) Str::ulid());
テスト中、Str::ulidメソッドが返す値を「偽装」すると便利な場合があります。これを実現するには、createUlidsUsingメソッドを使用します。
1use Symfony\Component\Uid\Ulid;2 3Str::createUlidsUsing(function () {4 return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');5});
ulidメソッドに通常のULIDの生成に戻すように指示するには、createUlidsNormallyメソッドを呼び出します。
1Str::createUlidsNormally();
Str::unwrap()
Str::unwrapメソッドは、指定した文字列の先頭と末尾から指定した文字列を削除します。
1use Illuminate\Support\Str;2 3Str::unwrap('-Laravel-', '-');4 5// Laravel6 7Str::unwrap('{framework: "Laravel"}', '{', '}');8 9// framework: "Laravel"
Str::uuid()
Str::uuidメソッドはUUID(バージョン4)を生成します。
1use Illuminate\Support\Str;2 3return (string) Str::uuid();
テスト中、Str::uuidメソッドが返す値を「偽装」すると便利な場合があります。これを実現するには、createUuidsUsingメソッドを使用します。
1use Ramsey\Uuid\Uuid;2 3Str::createUuidsUsing(function () {4 return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');5});
uuidメソッドに通常のUUIDの生成に戻すように指示するには、createUuidsNormallyメソッドを呼び出します。
1Str::createUuidsNormally();
Str::wordCount()
Str::wordCountメソッドは、文字列に含まれる単語の数を返します。
1use Illuminate\Support\Str;2 3Str::wordCount('Hello, world!'); // 2
Str::wordWrap()
Str::wordWrapメソッドは、文字列を指定した文字数で折り返します。
1 2``````php 3use Illuminate\Support\Str; 4 5$text = "The quick brown fox jumped over the lazy dog." 6 7Str::wordWrap($text, characters: 20, break: "<br />\n"); 8 9/*10The quick brown fox<br />11jumped over the lazy<br />12dog.13*/
Str::words()
Str::wordsメソッドは、文字列内の単語数を制限します。第3引数で追加の文字列をこのメソッドに渡し、切り詰めた文字列の末尾に追加する文字列を指定できます。
1 2``````php3use Illuminate\Support\Str;4 5return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');6 7// Perfectly balanced, as >>>
Str::wrap()
Str::wrapメソッドは、指定した文字列を追加の文字列または文字列のペアでラップします。
1 2``````php 3use Illuminate\Support\Str; 4 5Str::wrap('Laravel', '"'); 6 7// "Laravel" 8 9Str::wrap('is', before: 'This ', after: ' Laravel!');10 11// This is Laravel!
str()
str関数は、指定した文字列の新しいIlluminate\Support\Stringableインスタンスを返します。この関数はStr::ofメソッドと同じです。
1 2``````php3$string = str('Taylor')->append(' Otwell');4 5// 'Taylor Otwell'
str関数に引数を指定しない場合、関数はIlluminate\Support\Strのインスタンスを返します。
1 2``````php3$snake = str()->snake('FooBar');4 5// 'foo_bar'
trans()
trans関数は、言語ファイルを使用して、指定した翻訳キーを翻訳します。
1 2``````php3echo trans('messages.welcome');
指定した翻訳キーが存在しない場合、trans関数は指定したキーを返します。したがって、上記の例を使用すると、翻訳キーが存在しない場合、trans関数はmessages.welcomeを返します。
trans_choice()
trans_choice関数は、指定した翻訳キーを屈折させて翻訳します。
1echo trans_choice('messages.notifications', $unreadCount);
指定した翻訳キーが存在しない場合、trans_choice関数は指定したキーを返します。したがって、上記の例を使用すると、翻訳キーが存在しない場合、trans_choice関数はmessages.notificationsを返します。
Fluent文字列
Fluent文字列は、文字列値を操作するための、より流暢でオブジェクト指向のインターフェイスを提供します。これにより、従来の文字列操作と比較して、より読みやすい構文を使用して複数の文字列操作を連結できます。
after
afterメソッドは、文字列内の指定値より後のすべてを返します。文字列内に値が存在しない場合は、文字列全体が返されます。
1use Illuminate\Support\Str;2 3$slice = Str::of('This is my name')->after('This is');4 5// ' my name'
afterLast
afterLastメソッドは、文字列内で最後に出現した指定値より後のすべてを返します。文字列内に値が存在しない場合は、文字列全体が返されます。
1use Illuminate\Support\Str;2 3$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');4 5// 'Controller'
apa
apaメソッドは、APAガイドラインに従い、指定文字列をタイトルケースに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('a nice title uses the correct case')->apa();4 5// A Nice Title Uses the Correct Case
append
appendメソッドは、指定した値を文字列に追加します。
1use Illuminate\Support\Str;2 3$string = Str::of('Taylor')->append(' Otwell');4 5// 'Taylor Otwell'
ascii
asciiメソッドは、文字列をASCII値に音訳しようと試みます。
1use Illuminate\Support\Str;2 3$string = Str::of('ü')->ascii();4 5// 'u'
basename
basenameメソッドは、指定した文字列の末尾の名前コンポーネントを返します。
1use Illuminate\Support\Str;2 3$string = Str::of('/foo/bar/baz')->basename();4 5// 'baz'
必要であれば、末尾のコンポーネントから削除する「拡張子」を指定できます。
1use Illuminate\Support\Str;2 3$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');4 5// 'baz'
before
beforeメソッドは、文字列内の指定値より前のすべてを返します。
1use Illuminate\Support\Str;2 3$slice = Str::of('This is my name')->before('my name');4 5// 'This is '
beforeLast
beforeLastメソッドは、文字列内で最後に出現した指定値より前のすべてを返します。
1use Illuminate\Support\Str;2 3$slice = Str::of('This is my name')->beforeLast('is');4 5// 'This '
between
betweenメソッドは、2つの値に挟まれた文字列の部分を返します。
1use Illuminate\Support\Str;2 3$converted = Str::of('This is my name')->between('This', 'name');4 5// ' is my '
betweenFirst
betweenFirstメソッドは、2つの値に挟まれた文字列のうち、最短の部分を返します。
1use Illuminate\Support\Str;2 3$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');4 5// 'a'
camel
camelメソッドは、指定した文字列をcamelCaseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('foo_bar')->camel();4 5// 'fooBar'
charAt
charAtメソッドは、指定したインデックスの文字を返します。インデックスが範囲外の場合はfalseを返します。
1use Illuminate\Support\Str;2 3$character = Str::of('This is my name.')->charAt(6);4 5// 's'
classBasename
classBasenameメソッドは、指定したクラスの名前から名前空間を削除したクラス名を返します。
1use Illuminate\Support\Str;2 3$class = Str::of('Foo\Bar\Baz')->classBasename();4 5// 'Baz'
chopStart
chopStartメソッドは、指定値が文字列の先頭にある場合にのみ、その値の最初の出現箇所を削除します。
1use Illuminate\Support\Str;2 3$url = Str::of('https://laravel.dokyumento.jp')->chopStart('https://');4 5// 'laravel.com'
配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値が文字列から削除されます。
1use Illuminate\Support\Str;2 3$url = Str::of('https://laravel.dokyumento.jp')->chopStart(['https://', 'http://']);4 5// 'laravel.com'
chopEnd
chopEndメソッドは、指定値が文字列の末尾にある場合にのみ、その値の最後の出現箇所を削除します。
1use Illuminate\Support\Str;2 3$url = Str::of('https://laravel.dokyumento.jp')->chopEnd('.com');4 5// 'https://laravel'
配列を渡すこともできます。文字列が配列内のいずれかの値で終わる場合、その値が文字列から削除されます。
1use Illuminate\Support\Str;2 3$url = Str::of('https://laravel.dokyumento.jp')->chopEnd(['.com', '.io']);4 5// 'http://laravel'
contains
containsメソッドは、指定した文字列に指定値が含まれているかを判定します。デフォルトでこのメソッドは大文字と小文字を区別します。
1use Illuminate\Support\Str;2 3$contains = Str::of('This is my name')->contains('my');4 5// true
値の配列を渡して、指定文字列が配列内のいずれかの値を含んでいるかどうかを判断することもできます。
1use Illuminate\Support\Str;2 3$contains = Str::of('This is my name')->contains(['my', 'foo']);4 5// true
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$contains = Str::of('This is my name')->contains('MY', ignoreCase: true);4 5// true
containsAll
containsAllメソッドは、指定した文字列が、指定した配列内のすべての値を含んでいるかどうかを判定します。
1use Illuminate\Support\Str;2 3$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);4 5// true
ignoreCase引数をtrueに設定すると、大文字と小文字の区別を無効にできます。
1use Illuminate\Support\Str;2 3$containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);4 5// true
deduplicate
deduplicateメソッドは、指定した文字列内で連続する文字のインスタンスを1つのインスタンスに置き換えます。デフォルトでは、このメソッドはスペースの重複を削除します。
1use Illuminate\Support\Str;2 3$result = Str::of('The Laravel Framework')->deduplicate();4 5// The Laravel Framework
メソッドの第2引数として渡すことで、重複を削除する別の文字を指定できます。
1use Illuminate\Support\Str;2 3$result = Str::of('The---Laravel---Framework')->deduplicate('-');4 5// The-Laravel-Framework
dirname
dirnameメソッドは、指定した文字列の親ディレクトリ部分を返します。
1use Illuminate\Support\Str;2 3$string = Str::of('/foo/bar/baz')->dirname();4 5// '/foo/bar'
必要であれば、文字列から削除したいディレクトリレベルの数を指定できます。
1use Illuminate\Support\Str;2 3$string = Str::of('/foo/bar/baz')->dirname(2);4 5// '/foo'
endsWith
endsWithメソッドは、指定した文字列が指定値で終わるか判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('This is my name')->endsWith('name');4 5// true
値の配列を渡して、指定した文字列が配列内のいずれかの値で終わるかどうかを判断することもできます。
1use Illuminate\Support\Str;2 3$result = Str::of('This is my name')->endsWith(['name', 'foo']);4 5// true6 7$result = Str::of('This is my name')->endsWith(['this', 'foo']);8 9// false
exactly
exactlyメソッドは、指定した文字列が別の文字列と完全に一致するかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('Laravel')->exactly('Laravel');4 5// true
excerpt
excerptメソッドは、文字列内で最初に見つかったフレーズに一致する部分を、文字列から抜粋します。
1use Illuminate\Support\Str;2 3$excerpt = Str::of('This is my name')->excerpt('my', [4 'radius' => 35]);6 7// '...is my na...'
radiusオプション(デフォルトは100)で、切り詰めた文字列の両側に表示する文字数を定義できます。
さらに、omissionオプションを使用して、切り詰めた文字列の前後に付加する文字列を変更できます。
1use Illuminate\Support\Str;2 3$excerpt = Str::of('This is my name')->excerpt('name', [4 'radius' => 3,5 'omission' => '(...) '6]);7 8// '(...) my name'
explode
explodeメソッドは、指定したデリミタで文字列を分割し、分割された文字列の各セクションを含むコレクションを返します。
1use Illuminate\Support\Str;2 3$collection = Str::of('foo bar baz')->explode(' ');4 5// collect(['foo', 'bar', 'baz'])
finish
finishメソッドは、文字列がまだその値で終わっていない場合に、指定した値のインスタンスを1つ追加します。
1use Illuminate\Support\Str;2 3$adjusted = Str::of('this/string')->finish('/');4 5// this/string/6 7$adjusted = Str::of('this/string/')->finish('/');8 9// this/string/
headline
headlineメソッドは、大文字小文字の区切り、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字を大文字にしたスペース区切りの文字列に変換します。
1use Illuminate\Support\Str;2 3$headline = Str::of('taylor_otwell')->headline();4 5// Taylor Otwell6 7$headline = Str::of('EmailNotificationSent')->headline();8 9// Email Notification Sent
inlineMarkdown
inlineMarkdownメソッドは、CommonMarkを使用して、GitHubフレーバーのMarkdownをインラインHTMLに変換します。ただし、markdownメソッドとは異なり、生成されたすべてのHTMLをブロックレベル要素でラップしません。
1use Illuminate\Support\Str;2 3$html = Str::of('**Laravel**')->inlineMarkdown();4 5// <strong>Laravel</strong>
Markdownのセキュリティ
CommonMark Securityのドキュメントにあるように、デフォルトでMarkdownは生のHTMLをサポートしており、ユーザーの生の入力と合わせて使用するとクロスサイトスクリプティング(XSS)の脆弱性を引き起こします。html_inputオプションを使用して生のHTMLをエスケープまたは除去したり、allow_unsafe_linksオプションで安全でないリンクを許可するかを指定したりできます。生のHTMLの一部を許可する必要がある場合は、コンパイルしたMarkdownをHTML Purifierに通す必要があります。
1use Illuminate\Support\Str;2 3Str::of('Inject: <script>alert("Hello XSS!");</script>')->inlineMarkdown([4 'html_input' => 'strip',5 'allow_unsafe_links' => false,6]);7 8// Inject: alert("Hello XSS!");
is
isメソッドは、指定した文字列が指定したパターンに一致するかどうかを判定します。アスタリスクはワイルドカードとして使用できます。
1use Illuminate\Support\Str;2 3$matches = Str::of('foobar')->is('foo*');4 5// true6 7$matches = Str::of('foobar')->is('baz*');8 9// false
isAscii
isAsciiメソッドは、指定した文字列がASCII文字列であるかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('Taylor')->isAscii();4 5// true6 7$result = Str::of('ü')->isAscii();8 9// false
isEmpty
isEmptyメソッドは、指定した文字列が空であるかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of(' ')->trim()->isEmpty();4 5// true6 7$result = Str::of('Laravel')->trim()->isEmpty();8 9// false
isNotEmpty
isNotEmptyメソッドは、指定した文字列が空でないかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of(' ')->trim()->isNotEmpty();4 5// false6 7$result = Str::of('Laravel')->trim()->isNotEmpty();8 9// true
isJson
isJsonメソッドは、指定した文字列が有効なJSONであるかどうかを判定します。
1use Illuminate\Support\Str; 2 3$result = Str::of('[1,2,3]')->isJson(); 4 5// true 6 7$result = Str::of('{"first": "John", "last": "Doe"}')->isJson(); 8 9// true10 11$result = Str::of('{first: "John", last: "Doe"}')->isJson();12 13// false
isUlid
isUlidメソッドは、指定した文字列がULIDであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();4 5// true6 7$result = Str::of('Taylor')->isUlid();8 9// false
isUrl
isUrlメソッドは、指定した文字列がURLであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('http://example.com')->isUrl();4 5// true6 7$result = Str::of('Taylor')->isUrl();8 9// false
isUrlメソッドは、幅広いプロトコルを有効とみなします。しかし、isUrlメソッドにプロトコルを指定することで、有効とみなすプロトコルを指定できます。
1$result = Str::of('http://example.com')->isUrl(['http', 'https']);
isUuid
isUuidメソッドは、指定した文字列がUUIDであるかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();4 5// true6 7$result = Str::of('Taylor')->isUuid();8 9// false
kebab
kebabメソッドは、指定した文字列をkebab-caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('fooBar')->kebab();4 5// foo-bar
lcfirst
lcfirstメソッドは、指定した文字列の最初の文字を小文字にして返します。
1use Illuminate\Support\Str;2 3$string = Str::of('Foo Bar')->lcfirst();4 5// foo Bar
length
lengthメソッドは、指定した文字列の長さを返します。
1use Illuminate\Support\Str;2 3$length = Str::of('Laravel')->length();4 5// 7
limit
limitメソッドは、指定した文字列を指定した長さに切り詰めます。
1use Illuminate\Support\Str;2 3$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);4 5// The quick brown fox...
第2引数を渡して、切り詰めた文字列の末尾に追加する文字列を変更することもできます。
1$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');2 3// The quick brown fox (...)
文字列を切り詰める際に単語を完全に残したい場合は、preserveWords引数が利用できます。この引数がtrueの場合、文字列は最も近い完全な単語の境界で切り詰められます。
1$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true);2 3// The quick...
lower
lowerメソッドは、指定した文字列を小文字に変換します。
1use Illuminate\Support\Str;2 3$result = Str::of('LARAVEL')->lower();4 5// 'laravel'
markdown
markdownメソッドは、GitHubフレーバーのMarkdownをHTMLに変換します。
1use Illuminate\Support\Str; 2 3$html = Str::of('# Laravel')->markdown(); 4 5// <h1>Laravel</h1> 6 7$html = Str::of('# Taylor <b>Otwell</b>')->markdown([ 8 'html_input' => 'strip', 9]);10 11// <h1>Taylor Otwell</h1>
Markdownのセキュリティ
CommonMark Securityのドキュメントにあるように、デフォルトでMarkdownは生のHTMLをサポートしており、ユーザーの生の入力と合わせて使用するとクロスサイトスクリプティング(XSS)の脆弱性を引き起こします。html_inputオプションを使用して生のHTMLをエスケープまたは除去したり、allow_unsafe_linksオプションで安全でないリンクを許可するかを指定したりできます。生のHTMLの一部を許可する必要がある場合は、コンパイルしたMarkdownをHTML Purifierに通す必要があります。
1use Illuminate\Support\Str;2 3Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([4 'html_input' => 'strip',5 'allow_unsafe_links' => false,6]);7 8// <p>Inject: alert("Hello XSS!");</p>
mask
maskメソッドは、文字列の一部を繰り返し文字でマスクし、メールアドレスや電話番号などの文字列の一部を難読化するために使用します。
1use Illuminate\Support\Str;2 4 5// tay***************
必要であれば、maskメソッドの第3引数または第4引数に負の数を指定できます。これにより、メソッドは文字列の末尾から指定した距離でマスキングを開始します。
2 3// tay***@example.com4 6 7// tayl**********.com
match
matchメソッドは、指定した正規表現パターンに一致する文字列の部分を返します。
1use Illuminate\Support\Str;2 3$result = Str::of('foo bar')->match('/bar/');4 5// 'bar'6 7$result = Str::of('foo bar')->match('/foo (.*)/');8 9// 'bar'
matchAll
matchAllメソッドは、指定した正規表現パターンに一致する文字列の部分を含むコレクションを返します。
1use Illuminate\Support\Str;2 3$result = Str::of('bar foo bar')->matchAll('/bar/');4 5// collect(['bar', 'bar'])
式内でマッチンググループを指定すると、Laravelは最初のマッチンググループの一致のコレクションを返します。
1use Illuminate\Support\Str;2 3$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');4 5// collect(['un', 'ly']);
一致するものが見つからない場合は、空のコレクションが返されます。
isMatch
isMatchメソッドは、文字列が指定した正規表現に一致する場合にtrueを返します。
1use Illuminate\Support\Str;2 3$result = Str::of('foo bar')->isMatch('/foo (.*)/');4 5// true6 7$result = Str::of('laravel')->isMatch('/foo (.*)/');8 9// false
newLine
newLineメソッドは、文字列に「行末」文字を追加します。
1use Illuminate\Support\Str;2 3$padded = Str::of('Laravel')->newLine()->append('Framework');4 5// 'Laravel6// Framework'
padBoth
padBothメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の両側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::of('James')->padBoth(10, '_');4 5// '__James___'6 7$padded = Str::of('James')->padBoth(10);8 9// ' James '
padLeft
padLeftメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の左側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::of('James')->padLeft(10, '-=');4 5// '-=-=-James'6 7$padded = Str::of('James')->padLeft(10);8 9// ' James'
padRight
padRightメソッドは、PHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の右側を別の文字列でパディングします。
1use Illuminate\Support\Str;2 3$padded = Str::of('James')->padRight(10, '-');4 5// 'James-----'6 7$padded = Str::of('James')->padRight(10);8 9// 'James '
pipe
pipeメソッドを使用すると、現在の値を指定したCallableに渡すことで、文字列を変換できます。
1use Illuminate\Support\Str; 2use Illuminate\Support\Stringable; 3 4$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: '); 5 6// 'Checksum: a5c95b86291ea299fcbe64458ed12702' 7 8$closure = Str::of('foo')->pipe(function (Stringable $str) { 9 return 'bar';10});11 12// 'bar'
plural
pluralメソッドは、単数形の単語文字列を複数形に変換します。この関数は、Laravelの複数形変換機能がサポートするすべての言語をサポートしています。
1use Illuminate\Support\Str;2 3$plural = Str::of('car')->plural();4 5// cars6 7$plural = Str::of('child')->plural();8 9// children
関数の第2引数に整数を指定して、文字列の単数形または複数形を取得できます。
1use Illuminate\Support\Str;2 3$plural = Str::of('child')->plural(2);4 5// children6 7$plural = Str::of('child')->plural(1);8 9// child
position
positionメソッドは、文字列内で部分文字列が最初に出現する位置を返します。部分文字列が文字列内に存在しない場合は、falseが返されます。
1use Illuminate\Support\Str;2 3$position = Str::of('Hello, World!')->position('Hello');4 5// 06 7$position = Str::of('Hello, World!')->position('W');8 9// 7
prepend
prependメソッドは、指定した値を文字列の先頭に追加します。
1use Illuminate\Support\Str;2 3$string = Str::of('Framework')->prepend('Laravel ');4 5// Laravel Framework
remove
removeメソッドは、指定した値または値の配列を文字列から削除します。
1use Illuminate\Support\Str;2 3$string = Str::of('Arkansas is quite beautiful!')->remove('quite');4 5// Arkansas is beautiful!
また、第2パラメータとしてfalseを渡すと、文字列を削除する際に大文字と小文字の区別を無視できます。
repeat
repeatメソッドは、指定した文字列を繰り返します。
1use Illuminate\Support\Str;2 3$repeated = Str::of('a')->repeat(5);4 5// aaaaa
replace
replaceメソッドは、文字列内の指定した文字列を置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');4 5// Laravel 7.x
replaceメソッドは、caseSensitive引数も受け入れます。デフォルトでは、replaceメソッドは大文字と小文字を区別します。
1$replaced = Str::of('macOS 13.x')->replace(2 'macOS', 'iOS', caseSensitive: false3);
replaceArray
replaceArrayメソッドは、配列を使用して、文字列内の指定した値を順番に置き換えます。
1use Illuminate\Support\Str;2 3$string = 'The event will take place between ? and ?';4 5$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);6 7// The event will take place between 8:30 and 9:00
replaceFirst
replaceFirstメソッドは、文字列内で最初に出現した指定値を置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');4 5// a quick brown fox jumps over the lazy dog
replaceLast
replaceLastメソッドは、文字列内で最後に出現した指定値を置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');4 5// the quick brown fox jumps over a lazy dog
replaceMatches
replaceMatchesメソッドは、パターンに一致する文字列のすべての部分を指定した置換文字列に置き換えます。
1use Illuminate\Support\Str;2 3$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')4 5// '15015551000'
replaceMatchesメソッドはクロージャも受け入れます。このクロージャは、指定したパターンに一致する文字列の各部分に対して呼び出され、クロージャ内で置換ロジックを実行し、置換された値を返すことができます。
1use Illuminate\Support\Str;2 3$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {4 return '['.$matches[0].']';5});6 7// '[1][2][3]'
replaceStart
replaceStartメソッドは、指定値が文字列の先頭にある場合にのみ、その値の最初の出現箇所を置換します。
1use Illuminate\Support\Str;2 3$replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel');4 5// Laravel World6 7$replaced = Str::of('Hello World')->replaceStart('World', 'Laravel');8 9// Hello World
replaceEnd
replaceEndメソッドは、指定値が文字列の末尾にある場合にのみ、その値の最後の出現箇所を置換します。
1use Illuminate\Support\Str;2 3$replaced = Str::of('Hello World')->replaceEnd('World', 'Laravel');4 5// Hello Laravel6 7$replaced = Str::of('Hello World')->replaceEnd('Hello', 'Laravel');8 9// Hello World
scan
scanメソッドは、PHPのsscanf関数がサポートするフォーマットに従って、文字列からの入力をコレクションにパースします。
1use Illuminate\Support\Str;2 3$collection = Str::of('filename.jpg')->scan('%[^.].%s');4 5// collect(['filename', 'jpg'])
singular
singularメソッドは、文字列を単数形に変換します。この関数は、Laravelの複数形変換機能がサポートするすべての言語をサポートしています。
1use Illuminate\Support\Str;2 3$singular = Str::of('cars')->singular();4 5// car6 7$singular = Str::of('children')->singular();8 9// child
slug
slugメソッドは、指定した文字列からURLフレンドリーな「スラグ」を生成します。
1use Illuminate\Support\Str;2 3$slug = Str::of('Laravel Framework')->slug('-');4 5// laravel-framework
snake
snakeメソッドは、指定した文字列をsnake_caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('fooBar')->snake();4 5// foo_bar
split
splitメソッドは、正規表現を使用して文字列をコレクションに分割します。
1use Illuminate\Support\Str;2 3$segments = Str::of('one, two, three')->split('/[\s,]+/');4 5// collect(["one", "two", "three"])
squish
squishメソッドは、単語間の余分な空白を含む、文字列からすべての余分な空白を削除します。
1use Illuminate\Support\Str;2 3$string = Str::of(' laravel framework ')->squish();4 5// laravel framework
start
startメソッドは、文字列がまだその値で始まっていない場合に、指定した値のインスタンスを1つ追加します。
1use Illuminate\Support\Str;2 3$adjusted = Str::of('this/string')->start('/');4 5// /this/string6 7$adjusted = Str::of('/this/string')->start('/');8 9// /this/string
startsWith
startsWithメソッドは、指定した文字列が指定値で始まるか判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('This is my name')->startsWith('This');4 5// true
stripTags
stripTagsメソッドは、文字列からすべてのHTMLタグとPHPタグを削除します。
1use Illuminate\Support\Str;2 3$result = Str::of('<a href="https://laravel.dokyumento.jp">Taylor <b>Otwell</b></a>')->stripTags();4 5// Taylor Otwell6 7$result = Str::of('<a href="https://laravel.dokyumento.jp">Taylor <b>Otwell</b></a>')->stripTags('<b>');8 9// Taylor <b>Otwell</b>
studly
studlyメソッドは、指定した文字列をStudlyCaseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('foo_bar')->studly();4 5// FooBar
substr
substrメソッドは、指定された開始パラメータと長さパラメータで指定された文字列の一部を返します。
1use Illuminate\Support\Str;2 3$string = Str::of('Laravel Framework')->substr(8);4 5// Framework6 7$string = Str::of('Laravel Framework')->substr(8, 5);8 9// Frame
substrReplace
substrReplaceメソッドは、第2引数で指定された位置から始まり、第3引数で指定された文字数を置き換えることで、文字列の一部分のテキストを置き換えます。メソッドの第3引数に0を渡すと、文字列内の既存の文字を置き換えることなく、指定された位置に文字列を挿入します。
1use Illuminate\Support\Str;2 3$string = Str::of('1300')->substrReplace(':', 2);4 5// 13:6 7$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);8 9// The Laravel Framework
swap
swapメソッドは、PHPのstrtr関数を使用して、文字列内の複数の値を置換します。
1use Illuminate\Support\Str;2 3$string = Str::of('Tacos are great!')4 ->swap([5 'Tacos' => 'Burritos',6 'great' => 'fantastic',7 ]);8 9// Burritos are fantastic!
take
takeメソッドは、文字列の先頭から指定された文字数を返します。
1use Illuminate\Support\Str;2 3$taken = Str::of('Build something amazing!')->take(5);4 5// Build
tap
tapメソッドは、文字列自体に影響を与えることなく、文字列を調べたり操作したりできるように、文字列を指定したクロージャに渡します。クロージャから何が返されるかに関係なく、元の文字列がtapメソッドから返されます。
1use Illuminate\Support\Str; 2use Illuminate\Support\Stringable; 3 4$string = Str::of('Laravel') 5 ->append(' Framework') 6 ->tap(function (Stringable $string) { 7 dump('String after append: '.$string); 8 }) 9 ->upper();10 11// LARAVEL FRAMEWORK
test
testメソッドは、文字列が指定した正規表現パターンに一致するかどうかを判定します。
1use Illuminate\Support\Str;2 3$result = Str::of('Laravel Framework')->test('/Laravel/');4 5// true
title
titleメソッドは、指定した文字列をTitle Caseに変換します。
1use Illuminate\Support\Str;2 3$converted = Str::of('a nice title uses the correct case')->title();4 5// A Nice Title Uses The Correct Case
toBase64
toBase64メソッドは、指定した文字列をBase64に変換します。
1use Illuminate\Support\Str;2 3$base64 = Str::of('Laravel')->toBase64();4 5// TGFyYXZlbA==
toHtmlString
toHtmlStringメソッドは、指定した文字列をIlluminate\Support\HtmlStringのインスタンスに変換します。これはBladeテンプレートでレンダリングされる際にエスケープされません。
1use Illuminate\Support\Str;2 3$htmlString = Str::of('Nuno Maduro')->toHtmlString();
transliterate
transliterateメソッドは、指定した文字列を最も近いASCII表現に変換しようと試みます。
1use Illuminate\Support\Str;2 3$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate()4
trim
trimメソッドは、指定した文字列をトリムします。PHPネイティブのtrim関数とは異なり、Laravelのtrimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::of(' Laravel ')->trim();4 5// 'Laravel'6 7$string = Str::of('/Laravel/')->trim('/');8 9// 'Laravel'
ltrim
ltrimメソッドは、文字列の左側をトリムします。PHPネイティブのltrim関数とは異なり、Laravelのltrimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::of(' Laravel ')->ltrim();4 5// 'Laravel '6 7$string = Str::of('/Laravel/')->ltrim('/');8 9// 'Laravel/'
rtrim
rtrimメソッドは、指定した文字列の右側をトリムします。PHPネイティブのrtrim関数とは異なり、Laravelのrtrimメソッドはユニコードの空白文字も削除します。
1use Illuminate\Support\Str;2 3$string = Str::of(' Laravel ')->rtrim();4 5// ' Laravel'6 7$string = Str::of('/Laravel/')->rtrim('/');8 9// '/Laravel'
ucfirst
ucfirstメソッドは、指定した文字列の最初の文字を大文字にして返します。
1use Illuminate\Support\Str;2 3$string = Str::of('foo bar')->ucfirst();4 5// Foo bar
ucsplit
ucsplitメソッドは、指定した文字列を大文字でコレクションに分割します。
1use Illuminate\Support\Str;2 3$string = Str::of('Foo Bar')->ucsplit();4 5// collect(['Foo', 'Bar'])
unwrap
unwrapメソッドは、指定した文字列の先頭と末尾から指定した文字列を削除します。
1use Illuminate\Support\Str;2 3Str::of('-Laravel-')->unwrap('-');4 5// Laravel6 7Str::of('{framework: "Laravel"}')->unwrap('{', '}');8 9// framework: "Laravel"
upper
upperメソッドは、指定した文字列を大文字に変換します。
1use Illuminate\Support\Str;2 3$adjusted = Str::of('laravel')->upper();4 5// LARAVEL
when
whenメソッドは、指定した条件がtrueの場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('Taylor')5 ->when(true, function (Stringable $string) {6 return $string->append(' Otwell');7 });8 9// 'Taylor Otwell'
必要であれば、whenメソッドの第3パラメータとして別のクロージャを渡すことができます。このクロージャは、条件パラメータがfalseと評価された場合に実行されます。
whenContains
whenContainsメソッドは、文字列が指定した値を含んでいる場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('tony stark')5 ->whenContains('tony', function (Stringable $string) {6 return $string->title();7 });8 9// 'Tony Stark'
必要であれば、whenメソッドの第3パラメータとして別のクロージャを渡すことができます。このクロージャは、文字列が指定した値を含んでいない場合に実行されます。
値の配列を渡して、指定文字列が配列内のいずれかの値を含んでいるかどうかを判断することもできます。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('tony stark')5 ->whenContains(['tony', 'hulk'], function (Stringable $string) {6 return $string->title();7 });8 9// Tony Stark
whenContainsAll
whenContainsAllメソッドは、文字列が指定した部分文字列をすべて含んでいる場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('tony stark')5 ->whenContainsAll(['tony', 'stark'], function (Stringable $string) {6 return $string->title();7 });8 9// 'Tony Stark'
必要であれば、whenメソッドの第3パラメータとして別のクロージャを渡すことができます。このクロージャは、条件パラメータがfalseと評価された場合に実行されます。
whenEmpty
whenEmptyメソッドは、文字列が空の場合に、指定したクロージャを呼び出します。クロージャが値を返した場合、その値はwhenEmptyメソッドからも返されます。クロージャが値を返さない場合は、fluent文字列インスタンスが返されます。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of(' ')->whenEmpty(function (Stringable $string) {5 return $string->trim()->prepend('Laravel');6});7 8// 'Laravel'
whenNotEmpty
whenNotEmptyメソッドは、文字列が空でない場合に、指定したクロージャを呼び出します。クロージャが値を返した場合、その値はwhenNotEmptyメソッドからも返されます。クロージャが値を返さない場合は、fluent文字列インスタンスが返されます。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {5 return $string->prepend('Laravel ');6});7 8// 'Laravel Framework'
whenStartsWith
whenStartsWithメソッドは、文字列が指定した部分文字列で始まる場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {5 return $string->title();6});7 8// 'Disney World'
whenEndsWith
whenEndsWithメソッドは、文字列が指定した部分文字列で終わる場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {5 return $string->title();6});7 8// 'Disney World'
whenExactly
whenExactlyメソッドは、文字列が指定した文字列と完全に一致する場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {5 return $string->title();6});7 8// 'Laravel'
whenNotExactly
whenNotExactlyメソッドは、文字列が指定した文字列と完全に一致しない場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {5 return $string->title();6});7 8// 'Framework'
whenIs
whenIsメソッドは、文字列が指定したパターンに一致する場合に、指定したクロージャを呼び出します。アスタリスクはワイルドカードとして使用できます。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {5 return $string->append('/baz');6});7 8// 'foo/bar/baz'
whenIsAscii
whenIsAsciiメソッドは、文字列が7ビットASCIIである場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {5 return $string->title();6});7 8// 'Laravel'
whenIsUlid
whenIsUlidメソッドは、文字列が有効なULIDである場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2 3$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {4 return $string->substr(0, 8);5});6 7// '01gd6r36'
whenIsUuid
whenIsUuidメソッドは、文字列が有効なUUIDである場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {5 return $string->substr(0, 8);6});7 8// 'a0a2a2d2'
whenTest
whenTestメソッドは、文字列が指定した正規表現に一致する場合に、指定したクロージャを呼び出します。クロージャは、fluent文字列インスタンスを受け取ります。
1use Illuminate\Support\Str;2use Illuminate\Support\Stringable;3 4$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {5 return $string->title();6});7 8// 'Laravel Framework'
wordCount
wordCountメソッドは、文字列に含まれる単語の数を返します。
1use Illuminate\Support\Str;2 3Str::of('Hello, world!')->wordCount(); // 2
words
wordsメソッドは、文字列内の単語数を制限します。必要に応じて、切り詰めた文字列に追加する追加の文字列を指定できます。
1use Illuminate\Support\Str;2 3$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');4 5// Perfectly balanced, as >>>
wrap
wrapメソッドは、指定した文字列を追加の文字列または文字列のペアでラップします。
1use Illuminate\Support\Str;2 3Str::of('Laravel')->wrap('"');4 5// "Laravel"6 7Str::is('is')->wrap(before: 'This ', after: ' Laravel!');8 9// This is Laravel!