メインコンテンツまでスキップ

文字列

はじめに

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::contains Str::containsAll 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::toHtmlString 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

</div>

<a name="fluent-strings-method-list"></a>
### フルエント文字列

<div class="collection-method-list" markdown="1">

[after](#method-fluent-str-after)
[afterLast](#method-fluent-str-after-last)
[apa](#method-fluent-str-apa)
[append](#method-fluent-str-append)
[ascii](#method-fluent-str-ascii)
[basename](#method-fluent-str-basename)
[before](#method-fluent-str-before)
[beforeLast](#method-fluent-str-before-last)
[between](#method-fluent-str-between)
[betweenFirst](#method-fluent-str-between-first)
[camel](#method-fluent-str-camel)
[charAt](#method-fluent-str-char-at)
[classBasename](#method-fluent-str-class-basename)
[contains](#method-fluent-str-contains)
[containsAll](#method-fluent-str-contains-all)
[dirname](#method-fluent-str-dirname)
[endsWith](#method-fluent-str-ends-with)
[excerpt](#method-fluent-str-excerpt)
[exactly](#method-fluent-str-exactly)
[explode](#method-fluent-str-explode)
[finish](#method-fluent-str-finish)
[headline](#method-fluent-str-headline)
[inlineMarkdown](#method-fluent-str-inline-markdown)
[is](#method-fluent-str-is)
[isAscii](#method-fluent-str-is-ascii)
[isEmpty](#method-fluent-str-is-empty)
[isNotEmpty](#method-fluent-str-is-not-empty)
[isJson](#method-fluent-str-is-json)
[isUlid](#method-fluent-str-is-ulid)
[isUrl](#method-fluent-str-is-url)
[isUuid](#method-fluent-str-is-uuid)
[kebab](#method-fluent-str-kebab)
[lcfirst](#method-fluent-str-lcfirst)
[length](#method-fluent-str-length)
[limit](#method-fluent-str-limit)
[lower](#method-fluent-str-lower)
[markdown](#method-fluent-str-markdown)
[mask](#method-fluent-str-mask)
[match](#method-fluent-str-match)
[matchAll](#method-fluent-str-match-all)
[isMatch](#method-fluent-str-is-match)
[newLine](#method-fluent-str-new-line)
[padBoth](#method-fluent-str-padboth)
[padLeft](#method-fluent-str-padleft)
[padRight](#method-fluent-str-padright)
[pipe](#method-fluent-str-pipe)
[plural](#method-fluent-str-plural)
[position](#method-fluent-str-position)
[prepend](#method-fluent-str-prepend)
[remove](#method-fluent-str-remove)
[repeat](#method-fluent-str-repeat)
[replace](#method-fluent-str-replace)
[replaceArray](#method-fluent-str-replace-array)
[replaceFirst](#method-fluent-str-replace-first)
[replaceLast](#method-fluent-str-replace-last)
[replaceMatches](#method-fluent-str-replace-matches)
[replaceStart](#method-fluent-str-replace-start)
[replaceEnd](#method-fluent-str-replace-end)
[scan](#method-fluent-str-scan)
[singular](#method-fluent-str-singular)
[slug](#method-fluent-str-slug)
[snake](#method-fluent-str-snake)
[split](#method-fluent-str-split)
[squish](#method-fluent-str-squish)
[start](#method-fluent-str-start)
[startsWith](#method-fluent-str-starts-with)
[stripTags](#method-fluent-str-strip-tags)
[studly](#method-fluent-str-studly)
[substr](#method-fluent-str-substr)
[substrReplace](#method-fluent-str-substrreplace)
[swap](#method-fluent-str-swap)
[take](#method-fluent-str-take)
[tap](#method-fluent-str-tap)
[test](#method-fluent-str-test)
[title](#method-fluent-str-title)
[toBase64](#method-fluent-str-to-base64)
[trim](#method-fluent-str-trim)
[ltrim](#method-fluent-str-ltrim)
[rtrim](#method-fluent-str-rtrim)
[ucfirst](#method-fluent-str-ucfirst)
[ucsplit](#method-fluent-str-ucsplit)
[unwrap](#method-fluent-str-unwrap)
[upper](#method-fluent-str-upper)
[when](#method-fluent-str-when)
[whenContains](#method-fluent-str-when-contains)
[whenContainsAll](#method-fluent-str-when-contains-all)
[whenEmpty](#method-fluent-str-when-empty)
[whenNotEmpty](#method-fluent-str-when-not-empty)
[whenStartsWith](#method-fluent-str-when-starts-with)
[whenEndsWith](#method-fluent-str-when-ends-with)
[whenExactly](#method-fluent-str-when-exactly)
[whenNotExactly](#method-fluent-str-when-not-exactly)
[whenIs](#method-fluent-str-when-is)
[whenIsAscii](#method-fluent-str-when-is-ascii)
[whenIsUlid](#method-fluent-str-when-is-ulid)
[whenIsUuid](#method-fluent-str-when-is-uuid)
[whenTest](#method-fluent-str-when-test)
[wordCount](#method-fluent-str-word-count)
[words](#method-fluent-str-words)

文字列

__()

__ 関数は、指定された翻訳文字列または翻訳キーを使用して、言語ファイルを使って翻訳します:

    echo __('Welcome to our application');

echo __('messages.welcome');

指定された翻訳文字列またはキーが存在しない場合、__ 関数は指定された値を返します。したがって、上記の例を使用すると、その翻訳キーが存在しない場合、__ 関数は messages.welcome を返します。

class_basename()

class_basename 関数は、指定されたクラスのクラス名を、クラスの名前空間を取り除いたもので返します:

    $class = class_basename('Foo\Bar\Baz');

// Baz

e()

e 関数は、PHP の htmlspecialchars 関数を、double_encode オプションをデフォルトで true に設定して実行します:

    echo e('<html>foo</html>');

// &lt;html&gt;foo&lt;/html&gt;

preg_replace_array()

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()

Str::after メソッドは、文字列内の指定された値の後にあるすべてを返します。文字列内にその値が存在しない場合は、全体の文字列が返されます:

    use Illuminate\Support\Str;

$slice = Str::after('This is my name', 'This is');

// ' my name'

Str::afterLast()

Str::afterLast メソッドは、文字列内の最後に指定された値の後にあるすべてを返します。文字列内にその値が存在しない場合は、全体の文字列が返されます:

    use Illuminate\Support\Str;

$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');

// 'Controller'

Str::apa()

Str::apa メソッドは、指定された文字列を、APA ガイドラインに従ってタイトルケースに変換します:

    use Illuminate\Support\Str;

$title = Str::apa('Creating A Project');

// 'Creating a Project'

Str::ascii()

Str::ascii メソッドは、文字列を ASCII 値に変換しようとします:

    use Illuminate\Support\Str;

$slice = Str::ascii('û');

// 'u'

Str::before()

Str::beforeメソッドは、文字列内の指定された値の前のすべてを返します:

    use Illuminate\Support\Str;

$slice = Str::before('This is my name', 'my name');

// 'This is '

Str::beforeLast()

Str::beforeLastメソッドは、文字列内の指定された値の最後の出現箇所の前のすべてを返します:

    use Illuminate\Support\Str;

$slice = Str::beforeLast('This is my name', 'is');

// 'This '

Str::between()

Str::betweenメソッドは、2つの値の間の文字列の部分を返します:

    use Illuminate\Support\Str;

$slice = Str::between('This is my name', 'This', 'name');

// ' is my '

Str::betweenFirst()

Str::betweenFirstメソッドは、2つの値の間の文字列の最小可能な部分を返します:

    use Illuminate\Support\Str;

$slice = Str::betweenFirst('[a] bc [d]', '[', ']');

// 'a'

Str::camel()

Str::camelメソッドは、指定された文字列をcamelCaseに変換します:

    use Illuminate\Support\Str;

$converted = Str::camel('foo_bar');

// 'fooBar'

Str::charAt()

Str::charAtメソッドは、指定されたインデックスの文字を返します。インデックスが範囲外の場合、falseが返されます:

    use Illuminate\Support\Str;

$character = Str::charAt('This is my name.', 6);

// 's'

Str::contains()

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

Str::containsAll()

Str::containsAllメソッドは、指定された文字列が与えられた配列内のすべての値を含むかどうかを判定します:

    use Illuminate\Support\Str;

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

// true

Str::endsWith()

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()

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()

Str::finishメソッドは、指定された値が文字列で終わっていない場合に、その値を文字列に追加します:

    use Illuminate\Support\Str;

$adjusted = Str::finish('this/string', '/');

// this/string/

$adjusted = Str::finish('this/string/', '/');

// this/string/

Str::headline()

Str::headlineメソッドは、大文字、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字が大文字になるスペースで区切られた文字列に変換します:

    use Illuminate\Support\Str;

$headline = Str::headline('steve_jobs');

// Steve Jobs

$headline = Str::headline('EmailNotificationSent');

// Email Notification Sent

Str::inlineMarkdown()

Str::inlineMarkdownメソッドは、GitHub風のMarkdownをCommonMarkを使用してインラインHTMLに変換します。ただし、markdownメソッドとは異なり、生成されたすべてのHTMLをブロックレベルの要素でラップしません:

    use Illuminate\Support\Str;

$html = Str::inlineMarkdown('**Laravel**');

// <strong>Laravel</strong>

Markdownセキュリティ

デフォルトでは、Markdownは生のHTMLをサポートしており、生のユーザー入力と使用するとクロスサイトスクリプティング(XSS)の脆弱性が露出します。CommonMarkセキュリティドキュメントによれば、html_inputオプションを使用して生のHTMLをエスケープまたは削除し、allow_unsafe_linksオプションを使用して安全でないリンクを許可するかどうかを指定できます。一部の生のHTMLを許可する必要がある場合は、コンパイルされたMarkdownを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()

Str::isメソッドは、指定されたパターンに一致するかどうかを判断します。アスタリスクはワイルドカード値として使用できます:

    use Illuminate\Support\Str;

$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

Str::isAscii()

Str::isAsciiメソッドは、指定された文字列が7ビットASCIIであるかどうかを判断します:

    use Illuminate\Support\Str;

$isAscii = Str::isAscii('Taylor');

// true

$isAscii = Str::isAscii('ü');

// false

Str::isJson()

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()

Str::isUrlメソッドは、指定された文字列が有効なURLかどうかを判定します。

    use Illuminate\Support\Str;

$isUrl = Str::isUrl('http://example.com');

// true

$isUrl = Str::isUrl('laravel');

// false

isUrlメソッドは、幅広いプロトコルを有効と見なします。ただし、isUrlメソッドにそれらを指定して有効と見なすプロトコルを提供することができます。

    $isUrl = Str::isUrl('http://example.com', ['http', 'https']);

Str::isUlid()

Str::isUlidメソッドは、指定された文字列が有効なULIDかどうかを判定します。

    use Illuminate\Support\Str;

$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');

// true

$isUlid = Str::isUlid('laravel');

// false

Str::isUuid()

Str::isUuidメソッドは、指定された文字列が有効なUUIDかどうかを判定します。

    use Illuminate\Support\Str;

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

Str::kebab()

Str::kebabメソッドは、指定された文字列をkebab-caseに変換します。

    use Illuminate\Support\Str;

$converted = Str::kebab('fooBar');

// foo-bar

Str::lcfirst()

Str::lcfirstメソッドは、最初の文字が小文字になった指定された文字列を返します。

    use Illuminate\Support\Str;

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

// foo Bar

Str::length()

Str::lengthメソッドは、指定された文字列の長さを返します。

    use Illuminate\Support\Str;

$length = Str::length('Laravel');

// 7

Str::limit()

Str::limitメソッドは、指定された長さに文字列を切り詰めます。

    use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox...

切り詰められた文字列の末尾に追加される文字列を変更するために、メソッドに第三引数を渡すことができます。

    use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

Str::lower()

Str::lowerメソッドは、指定された文字列を小文字に変換します。

    use Illuminate\Support\Str;

$converted = Str::lower('LARAVEL');

// laravel

Str::markdown()

Str::markdownメソッドは、GitHub風のMarkdownをCommonMarkを使用して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は生のHTMLをサポートしており、生のユーザー入力と一緒に使用すると、クロスサイトスクリプティング(XSS)の脆弱性を露出します。CommonMarkセキュリティドキュメントによれば、html_inputオプションを使用して生のHTMLをエスケープまたは削除し、allow_unsafe_linksオプションを使用して安全でないリンクを許可するかどうかを指定できます。一部の生のHTMLを許可する必要がある場合は、コンパイルされたMarkdownを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()

Str::maskメソッドは、文字列の一部を繰り返しの文字でマスクし、電子メールアドレスや電話番号などの文字列のセグメントを曖昧化するために使用できます:

    use Illuminate\Support\Str;

$string = Str::mask('taylor@example.com', '*', 3);

// tay***************

必要に応じて、maskメソッドの3番目の引数に負の数値を指定することで、文字列の末尾からの指定された距離でマスクを開始するようにメソッドに指示できます:

    $string = Str::mask('taylor@example.com', '*', -15, 3);

// tay***@example.com

Str::orderedUuid()

Str::orderedUuidメソッドは、「タイムスタンプ優先」UUIDを生成し、インデックス付きのデータベース列に効率的に保存できます。このメソッドを使用して生成された各UUIDは、以前にこのメソッドを使用して生成されたUUIDの後に並べられます:

    use Illuminate\Support\Str;

return (string) Str::orderedUuid();

Str::padBoth()

Str::padBothメソッドは、PHPのstr_pad関数をラップし、別の文字列で文字列の両側を埋めて、最終的な文字列が所定の長さに達するまで埋めます:

    use Illuminate\Support\Str;

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

// '__James___'

$padded = Str::padBoth('James', 10);

// ' James '

Str::padLeft()

Str::padLeftメソッドは、PHPのstr_pad関数をラップし、別の文字列で文字列の左側を埋めて、最終的な文字列が所定の長さに達するまで埋めます:

    use Illuminate\Support\Str;

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

// '-=-=-James'

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

// ' James'

Str::padRight()

Str::padRightメソッドは、PHPのstr_pad関数をラップし、別の文字列で文字列の右側を埋めて、最終的な文字列が所定の長さに達するまで埋めます:

    use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James '

Str::password()

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::plural()

Str::pluralメソッドは、単数形の単語文字列を複数形に変換します。この関数は、Laravelの複数形変換機能でサポートされている言語をサポートしています:

    use Illuminate\Support\Str;

$plural = Str::plural('car');

// cars

$plural = Str::plural('child');

// children

関数に2番目の引数として整数を指定すると、文字列の単数形または複数形を取得できます:

    use Illuminate\Support\Str;

$plural = Str::plural('child', 2);

// children

$singular = Str::plural('child', 1);

// child

Str::pluralStudly()

Str::pluralStudlyメソッドは、スタッドリーキャメルケース形式でフォーマットされた単数形の単語文字列を複数形に変換します。この関数は、Laravelの複数形変換機能でサポートされている言語をサポートしています:

    use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman');

// VerifiedHumans

$plural = Str::pluralStudly('UserFeedback');

// UserFeedback

関数に2番目の引数として整数を指定すると、文字列の単数形または複数形を取得できます:

    use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman', 2);

// VerifiedHumans

$singular = Str::pluralStudly('VerifiedHuman', 1);

// VerifiedHuman

Str::position()

Str::positionメソッドは、文字列内の部分文字列の最初の出現位置を返します。指定された文字列内に部分文字列が存在しない場合、falseが返されます:

    use Illuminate\Support\Str;

$position = Str::position('Hello, World!', 'Hello');

// 0

$position = Str::position('Hello, World!', 'W');

// 7

Str::random()

Str::randomメソッドは、指定された長さのランダムな文字列を生成します。この関数は、PHPのrandom_bytes関数を使用します:

    use Illuminate\Support\Str;

$random = Str::random(40);

テスト中に、Str::randomメソッドによって返される値を「偽造」することが役立つ場合があります。これを行うには、createRandomStringsUsingメソッドを使用できます:

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

randomメソッドが通常通りにランダムな文字列を生成するように指示するには、createRandomStringsNormallyメソッドを呼び出すことができます:

    Str::createRandomStringsNormally();

Str::remove()

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.

removeメソッドに3番目の引数としてfalseを渡すと、文字列を削除する際に大文字と小文字を区別しません。

Str::repeat()

Str::repeatメソッドは、指定された文字列を繰り返します。

use Illuminate\Support\Str;

$string = 'a';

$repeat = Str::repeat($string, 5);

// aaaaa

Str::replace()

Str::replaceメソッドは、文字列内の指定された文字列を置換します。

    use Illuminate\Support\Str;

$string = 'Laravel 10.x';

$replaced = Str::replace('10.x', '11.x', $string);

// Laravel 11.x

replaceメソッドはcaseSensitive引数も受け入れます。デフォルトでは、replaceメソッドは大文字と小文字を区別します。

    Str::replace('Framework', 'Laravel', caseSensitive: false);

Str::replaceArray()

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()

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()

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()

Str::replaceMatchesメソッドは、指定された置換文字列と一致する文字列のすべての部分を置換します。

    use Illuminate\Support\Str;

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

// '15015551000'

replaceMatchesメソッドは、指定されたパターンに一致する文字列の各部分に対して呼び出されるクロージャを受け入れます。これにより、クロージャ内で置換ロジックを実行し、置換された値を返すことができます。

    use Illuminate\Support\Str;

$replaced = Str::replaceMatches('/\d/', function (array $matches) {
return '['.$matches[0].']';
}, '123');

// '[1][2][3]'

Str::replaceStart()

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()

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()

Str::reverseメソッドは、指定された文字列を逆順にします。

    use Illuminate\Support\Str;

$reversed = Str::reverse('Hello World');

// dlroW olleH

Str::singular()

Str::singularメソッドは、文字列を単数形に変換します。この関数は、Laravelの複数形変換機能でサポートされている任意の言語をサポートしています。

    use Illuminate\Support\Str;

$singular = Str::singular('cars');

// car

$singular = Str::singular('children');

// child

Str::slug()

Str::slugメソッドは、指定された文字列からURLに適した「スラッグ」を生成します。

    use Illuminate\Support\Str;

$slug = Str::slug('Laravel 5 Framework', '-');

// laravel-5-framework

Str::snake()

Str::snakeメソッドは、指定された文字列をsnake_caseに変換します。

    use Illuminate\Support\Str;

$converted = Str::snake('fooBar');

// foo_bar

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

// foo-bar

Str::squish()

Str::squishメソッドは、文字列から余分な空白をすべて削除します。単語間の余分な空白も含まれます。

    use Illuminate\Support\Str;

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

// laravel framework

Str::start()

Str::startメソッドは、文字列が指定された値で始まっていない場合に、その値を文字列に追加します。

    use Illuminate\Support\Str;

$adjusted = Str::start('this/string', '/');

// /this/string

$adjusted = Str::start('/this/string', '/');

// /this/string

Str::startsWith()

Str::startsWithメソッドは、指定された文字列が指定された値で始まるかどうかを判定します。

    use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

可能な値の配列が渡された場合、startsWithメソッドは、文字列が指定された値のいずれかで始まる場合にtrueを返します。

    $result = Str::startsWith('This is my name', ['This', 'That', 'There']);

// true

Str::studly()

Str::studlyメソッドは、指定された文字列をStudlyCaseに変換します。

    use Illuminate\Support\Str;

$converted = Str::studly('foo_bar');

// FooBar

Str::substr()

Str::substrメソッドは、開始位置と長さのパラメータで指定された文字列の一部を返します。

    use Illuminate\Support\Str;

$converted = Str::substr('The Laravel Framework', 4, 7);

// Laravel

Str::substrCount()

Str::substrCountメソッドは、指定された文字列内で指定された値の出現回数を返します。

    use Illuminate\Support\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str::substrReplace()

Str::substrReplaceメソッドは、指定された位置から開始して、指定された文字数を置換する文字列内の一部を置換します。メソッドの第4引数に0を渡すと、指定された位置に文字列を挿入し、文字列内の既存の文字を置換しません。

    use Illuminate\Support\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str::swap()

Str::swapメソッドは、PHPのstrtr関数を使用して指定された文字列内の複数の値を置換します。

    use Illuminate\Support\Str;

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

// Burritos are fantastic!

Str::take()

Str::takeメソッドは、文字列の先頭から指定された文字数を返します。

    use Illuminate\Support\Str;

$taken = Str::take('Build something amazing!', 5);

// Build

Str::title()

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()

Str::toBase64メソッドは、指定された文字列をBase64に変換します。

    use Illuminate\Support\Str;

$base64 = Str::toBase64('Laravel');

// TGFyYXZlbA==

Str::toHtmlString()

Str::toHtmlStringメソッドは、文字列インスタンスをIlluminate\Support\HtmlStringのインスタンスに変換し、Bladeテンプレートで表示できるようにします。

    use Illuminate\Support\Str;

$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::trim()

Str::trimメソッドは、指定された文字列の先頭と末尾から空白(または他の文字)を削除します。PHPのネイティブのtrim関数とは異なり、Str::trimメソッドはUnicode空白文字も削除します。

    use Illuminate\Support\Str;

$string = Str::trim(' foo bar ');

// 'foo bar'

Str::ltrim()

Str::ltrimメソッドは、指定された文字列の先頭から空白(または他の文字)を削除します。PHPのネイティブのltrim関数とは異なり、Str::ltrimメソッドはUnicode空白文字も削除します。

    use Illuminate\Support\Str;

$string = Str::ltrim(' foo bar ');

// 'foo bar '

Str::rtrim()

Str::rtrimメソッドは、指定された文字列の末尾から空白(またはその他の文字)を取り除きます。PHPのネイティブのrtrim関数とは異なり、Str::rtrimメソッドはUnicode空白文字も削除します。

    use Illuminate\Support\Str;

$string = Str::rtrim(' foo bar ');

// ' foo bar'

Str::ucfirst()

Str::ucfirstメソッドは、指定された文字列の最初の文字を大文字にして返します。

    use Illuminate\Support\Str;

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

// Foo bar

Str::ucsplit()

Str::ucsplitメソッドは、大文字の文字によって指定された文字列を配列に分割します。

    use Illuminate\Support\Str;

$segments = Str::ucsplit('FooBar');

// [0 => 'Foo', 1 => 'Bar']

Str::upper()

Str::upperメソッドは、指定された文字列を大文字に変換します。

    use Illuminate\Support\Str;

$string = Str::upper('laravel');

// LARAVEL

Str::ulid()

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');
});

ulidメソッドが通常のULIDの生成に戻るように指示するには、createUlidsNormallyメソッドを呼び出すことができます。

    Str::createUlidsNormally();

Str::unwrap()

Str::unwrapメソッドは、指定された文字列から先頭と末尾の指定された文字列を削除します。

    use Illuminate\Support\Str;

Str::unwrap('-Laravel-', '-');

// Laravel

Str::unwrap('{framework: "Laravel"}', '{', '}');

// framework: "Laravel"

Str::uuid()

Str::uuidメソッドは、UUID(バージョン4)を生成します。

    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');
});

uuid メソッドに通常の UUID を生成するよう指示するには、createUuidsNormally メソッドを呼び出すことができます:

    Str::createUuidsNormally();

Str::wordCount()

Str::wordCount メソッドは、文字列が含む単語の数を返します:

use Illuminate\Support\Str;

Str::wordCount('Hello, world!'); // 2

Str::wordWrap()

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()

Str::words メソッドは、文字列内の単語の数を制限します。このメソッドの第三引数を使用して、切り詰められた文字列の末尾にどの文字列を追加するかを指定することもできます:

    use Illuminate\Support\Str;

return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');

// Perfectly balanced, as >>>

Str::wrap()

Str::wrap メソッドは、指定された文字列または文字列のペアで文字列を囲みます:

    use Illuminate\Support\Str;

Str::wrap('Laravel', '"');

// "Laravel"

Str::wrap('is', before: 'This ', after: ' Laravel!');

// This is Laravel!

str()

str 関数は、指定された文字列の新しい Illuminate\Support\Stringable インスタンスを返します。この関数は Str::of メソッドと同等です:

    $string = str('Taylor')->append(' Otwell');

// 'Taylor Otwell'

str 関数に引数が指定されていない場合、この関数は Illuminate\Support\Str のインスタンスを返します:

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

// 'foo_bar'

trans()

trans 関数は、指定された翻訳キーを使用して 言語ファイル を翻訳します:

    echo trans('messages.welcome');

指定された翻訳キーが存在しない場合、trans 関数は指定されたキーを返します。したがって、上記の例を使用すると、翻訳キーが存在しない場合、trans 関数は messages.welcome を返します。

trans_choice()

trans_choice 関数は、指定された翻訳キーを屈折形で翻訳します:

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

指定された翻訳キーが存在しない場合、trans_choice 関数は指定されたキーを返します。したがって、上記の例を使用すると、翻訳キーが存在しない場合、trans_choice 関数は messages.notifications を返します。

流暢な文字列

流暢な文字列は、文字列値を扱うためのより流暢でオブジェクト指向のインターフェースを提供し、従来の文字列操作に比べてより読みやすい構文を使用して複数の文字列操作を連鎖させることができます。

after

after メソッドは、文字列内の指定された値の後ろにあるすべてを返します。文字列内にその値が存在しない場合は、全体の文字列が返されます:

    use Illuminate\Support\Str;

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

// ' my name'

afterLast

afterLast メソッドは、文字列内の指定された値の最後の出現後にあるすべてを返します。文字列内にその値が存在しない場合は、全体の文字列が返されます:

    use Illuminate\Support\Str;

$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');

// 'Controller'

apa

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

append メソッドは、指定された値を文字列に追加します:

    use Illuminate\Support\Str;

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

// 'Taylor Otwell'

ascii

ascii メソッドは、文字列をASCII値に変換しようとします:

    use Illuminate\Support\Str;

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

// 'u'

basename

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

before メソッドは、文字列内の指定された値の前にあるすべてを返します:

    use Illuminate\Support\Str;

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

// 'This is '

beforeLast

beforeLast メソッドは、文字列内の指定された値の最後の出現の前にあるすべてを返します:

    use Illuminate\Support\Str;

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

// 'This '

between

betweenメソッドは、2つの値の間の文字列の部分を返します:

    use Illuminate\Support\Str;

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

// ' is my '

betweenFirst

betweenFirstメソッドは、2つの値の間の可能な限り最小の文字列部分を返します:

    use Illuminate\Support\Str;

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

// 'a'

camel

camelメソッドは、指定された文字列をcamelCaseに変換します:

    use Illuminate\Support\Str;

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

// 'fooBar'

charAt

charAtメソッドは、指定されたインデックスの文字を返します。インデックスが範囲外の場合は、falseが返されます:

    use Illuminate\Support\Str;

$character = Str::of('This is my name.')->charAt(6);

// 's'

classBasename

classBasenameメソッドは、指定されたクラスのクラス名を、クラスの名前空間を削除したもので返します:

    use Illuminate\Support\Str;

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

// 'Baz'

contains

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

containsAll

containsAllメソッドは、指定された文字列が指定された配列内のすべての値を含むかどうかを判定します:

    use Illuminate\Support\Str;

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

// true

dirname

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'

excerpt

excerptメソッドは、文字列内で最初に出現するフレーズに一致する部分を抽出します:

    use Illuminate\Support\Str;

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

// '...is my na...'

radiusオプションは、デフォルトで100に設定されており、切り詰められた文字列の両側に表示される文字数を定義できます。

    use Illuminate\Support\Str;

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

// '(...) my name'

endsWith

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

exactly メソッドは、指定された文字列が他の文字列と完全に一致するかどうかを判定します:

    use Illuminate\Support\Str;

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

// true

explode

explode メソッドは、指定された区切り文字で文字列を分割し、分割された各セクションを含むコレクションを返します:

    use Illuminate\Support\Str;

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

// collect(['foo', 'bar', 'baz'])

finish

finish メソッドは、文字列が指定された値で終わっていない場合に、その値の単一のインスタンスを文字列に追加します:

    use Illuminate\Support\Str;

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

// this/string/

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

// this/string/

headline

headline メソッドは、大文字、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字が大文字になるスペース区切りの文字列に変換します:

    use Illuminate\Support\Str;

$headline = Str::of('taylor_otwell')->headline();

// Taylor Otwell

$headline = Str::of('EmailNotificationSent')->headline();

// Email Notification Sent

inlineMarkdown

inlineMarkdown メソッドは、GitHub風のMarkdownを CommonMark を使用してインラインのHTMLに変換します。ただし、markdown メソッドとは異なり、生成されたすべてのHTMLをブロックレベルの要素でラップしません:

    use Illuminate\Support\Str;

$html = Str::of('**Laravel**')->inlineMarkdown();

// <strong>Laravel</strong>

Markdown セキュリティ

デフォルトでは、Markdown は raw HTML をサポートしており、これは raw ユーザー入力と使用すると Cross-Site Scripting (XSS) 脆弱性を露出します。CommonMark Security documentation によると、html_input オプションを使用して raw HTML をエスケープまたは削除し、allow_unsafe_links オプションを使用して安全でないリンクを許可するかどうかを指定できます。一部の raw HTML を許可する必要がある場合は、コンパイルされた Markdown を HTML Purifier を通して渡す必要があります:

    use Illuminate\Support\Str;

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

// Inject: alert(&quot;Hello XSS!&quot;);

is

isメソッドは、指定されたパターンに一致するかどうかを判定します。アスタリスクはワイルドカード値として使用できます。

    use Illuminate\Support\Str;

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

// true

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

// false

isAscii

isAsciiメソッドは、指定された文字列がASCII文字列かどうかを判定します。

    use Illuminate\Support\Str;

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

// true

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

// false

isEmpty

isEmptyメソッドは、指定された文字列が空かどうかを判定します。

    use Illuminate\Support\Str;

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

// true

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

// false

isNotEmpty

isNotEmptyメソッドは、指定された文字列が空でないかを判定します。

    use Illuminate\Support\Str;

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

// false

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

// true

isJson

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

isUlidメソッドは、指定された文字列がULIDかどうかを判定します。

    use Illuminate\Support\Str;

$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();

// true

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

// false

isUrl

isUrlメソッドは、指定された文字列がURLかどうかを判定します。

    use Illuminate\Support\Str;

$result = Str::of('http://example.com')->isUrl();

// true

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

// false

isUrlメソッドは、幅広いプロトコルを有効と見なします。ただし、isUrlメソッドにそれらを指定して有効と見なすべきプロトコルを提供することができます。

    $result = Str::of('http://example.com')->isUrl(['http', 'https']);

isUuid

isUuidメソッドは、指定された文字列がUUIDかどうかを判定します。

    use Illuminate\Support\Str;

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

// true

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

// false

kebab

kebabメソッドは、指定された文字列をkebab-caseに変換します。

    use Illuminate\Support\Str;

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

// foo-bar

lcfirst

lcfirstメソッドは、最初の文字が小文字になった指定された文字列を返します。

    use Illuminate\Support\Str;

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

// foo Bar


length

lengthメソッドは、指定された文字列の長さを返します。

    use Illuminate\Support\Str;

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

// 7

limitメソッドは、指定された長さに文字列を切り詰めます:

    use Illuminate\Support\Str;

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

// The quick brown fox...

切り詰められた文字列の末尾に追加される文字列を変更するために、第2引数を渡すこともできます:

    use Illuminate\Support\Str;

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

// The quick brown fox (...)

lower

lowerメソッドは、指定された文字列を小文字に変換します:

    use Illuminate\Support\Str;

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

// 'laravel'

markdown

markdownメソッドは、GitHub風のMarkdownをHTMLに変換します:

    use Illuminate\Support\Str;

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

// <h1>Laravel</h1>

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

// <h1>Taylor Otwell</h1>

Markdownセキュリティ

デフォルトでは、Markdownは生のHTMLをサポートしており、生のユーザー入力と一緒に使用すると、クロスサイトスクリプティング(XSS)の脆弱性を露出します。CommonMarkセキュリティドキュメントに従い、html_inputオプションを使用して生のHTMLをエスケープまたは削除し、allow_unsafe_linksオプションを使用して安全でないリンクを許可するかどうかを指定できます。一部の生のHTMLを許可する必要がある場合は、コンパイルされたMarkdownをHTML Purifierを通して渡す必要があります:

    use Illuminate\Support\Str;

Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);

// <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

mask

maskメソッドは、文字列の一部を繰り返し文字でマスクし、電子メールアドレスや電話番号などの文字列のセグメントを曖昧化するために使用できます:

    use Illuminate\Support\Str;

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

// tay***************

必要に応じて、maskメソッドの第3引数または第4引数に負の数値を指定することができ、これによりメソッドが文字列の末尾からの指定された距離でマスキングを開始するように指示できます:

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

// tay***@example.com

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

// tayl**********.com

match

matchメソッドは、指定された正規表現パターンに一致する文字列の部分を返します:

    use Illuminate\Support\Str;

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

// 'bar'

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

// 'bar'

matchAll

matchAllメソッドは、指定された正規表現パターンに一致する文字列の部分を含むコレクションを返します:

    use Illuminate\Support\Str;

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

// collect(['bar', 'bar'])

式内で一致するグループを指定すると、Laravelは最初の一致するグループの一致を含むコレクションを返します:

    use Illuminate\Support\Str;

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

// collect(['un', 'ly']);

一致するものが見つからない場合、空のコレクションが返されます。

isMatch

isMatch メソッドは、文字列が指定された正規表現と一致する場合に true を返します:

    use Illuminate\Support\Str;

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

// true

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

// false

newLine

newLine メソッドは、文字列に "行末" 文字を追加します:

    use Illuminate\Support\Str;

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

// 'Laravel
// Framework'

padBoth

padBoth メソッドは、PHP の str_pad 関数をラップし、別の文字列で文字列の両側を指定した長さになるまでパディングします:

    use Illuminate\Support\Str;

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

// '__James___'

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

// ' James '

padLeft

padLeft メソッドは、PHP の str_pad 関数をラップし、別の文字列で文字列の左側を指定した長さになるまでパディングします:

    use Illuminate\Support\Str;

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

// '-=-=-James'

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

// ' James'

padRight

padRight メソッドは、PHP の str_pad 関数をラップし、別の文字列で文字列の右側を指定した長さになるまでパディングします:

    use Illuminate\Support\Str;

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

// 'James-----'

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

// 'James '

pipe

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'

plural

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

position

position メソッドは、文字列内の部分文字列の最初の出現位置を返します。文字列内に部分文字列が存在しない場合、false が返されます:

    use Illuminate\Support\Str;

$position = Str::of('Hello, World!')->position('Hello');

// 0

$position = Str::of('Hello, World!')->position('W');

// 7

prepend

prependメソッドは、指定された値を文字列の先頭に追加します:

    use Illuminate\Support\Str;

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

// Laravel Framework

remove

removeメソッドは、指定された値または値の配列を文字列から削除します:

    use Illuminate\Support\Str;

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

// Arkansas is beautiful!

文字列を削除する際に大文字と小文字を区別しないようにするには、第2引数としてfalseを渡すこともできます。

repeat

repeatメソッドは、指定された文字列を繰り返します:

use Illuminate\Support\Str;

$repeated = Str::of('a')->repeat(5);

// aaaaa

replace

replaceメソッドは、文字列内の指定された文字列を置換します:

    use Illuminate\Support\Str;

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

// Laravel 7.x

replaceメソッドはcaseSensitive引数も受け入れます。デフォルトでは、replaceメソッドは大文字と小文字を区別します:

    $replaced = Str::of('macOS 13.x')->replace(
'macOS', 'iOS', caseSensitive: false
);

replaceArray

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

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

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

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メソッドは、文字列の先頭に指定された値が現れる場合にのみ、最初の出現箇所を置換します:

    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

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

scanメソッドは、sscanf PHP関数でサポートされている形式に従って、文字列から入力を解析します:

    use Illuminate\Support\Str;

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

// collect(['filename', 'jpg'])

singular

singularメソッドは、文字列を単数形に変換します。この関数は、Laravelの複数形変換機能でサポートされている言語をサポートしています:

    use Illuminate\Support\Str;

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

// car

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

// child

slug

slugメソッドは、指定された文字列からURLに適した「スラッグ」を生成します:

    use Illuminate\Support\Str;

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

// laravel-framework

snake

snakeメソッドは、指定された文字列をsnake_caseに変換します:

    use Illuminate\Support\Str;

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

// foo_bar

split

splitメソッドは、正規表現を使用して文字列をコレクションに分割します:

    use Illuminate\Support\Str;

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

// collect(["one", "two", "three"])

squish

squishメソッドは、文字列から余分な空白をすべて削除します。単語間の余分な空白も含まれます:

    use Illuminate\Support\Str;

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

// laravel framework

start

startメソッドは、指定された値で文字列がまだ開始されていない場合に、その値の単一のインスタンスを文字列に追加します:

    use Illuminate\Support\Str;

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

// /this/string

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

// /this/string

startsWith

startsWithメソッドは、指定された文字列が指定された値で始まるかどうかを判定します:

    use Illuminate\Support\Str;

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

// true

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

studlyメソッドは、指定された文字列をStudlyCaseに変換します:

    use Illuminate\Support\Str;

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

// FooBar

substr

substrメソッドは、指定された開始位置と長さのパラメータで指定された文字列の一部を返します:

    use Illuminate\Support\Str;

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

// Framework

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

// Frame

substrReplace

substrReplaceメソッドは、文字列の一部でテキストを置換し、第2引数で指定された位置から開始し、第3引数で指定された文字数を置換します。メソッドの第3引数に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

swapメソッドは、PHPのstrtr関数を使用して文字列内の複数の値を置換します:

    use Illuminate\Support\Str;

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

// Burritos are fantastic!

take

takeメソッドは、文字列の先頭から指定された数の文字を返します:

    use Illuminate\Support\Str;

$taken = Str::of('Build something amazing!')->take(5);

// Build

tap

tapメソッドは、指定されたクロージャに文字列を渡し、文字列自体に影響を与えずに文字列を調査および操作できるようにします。tapメソッドによって返されるのは、クロージャによって返される値に関係なく、元の文字列です:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// LARAVEL FRAMEWORK

test

testメソッドは、文字列が指定された正規表現パターンに一致するかどうかを判断します:

    use Illuminate\Support\Str;

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

// true

title

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()

toBase64メソッドは、指定された文字列をBase64に変換します:

    use Illuminate\Support\Str;

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

// TGFyYXZlbA==

trim

trim メソッドは指定された文字列をトリムします。PHP のネイティブ trim 関数とは異なり、Laravel の trim メソッドはユニコードの空白文字も削除します。

    use Illuminate\Support\Str;

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

// 'Laravel'

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

// 'Laravel'

ltrim

ltrim メソッドは文字列の左側をトリムします。PHP のネイティブ ltrim 関数とは異なり、Laravel の ltrim メソッドはユニコードの空白文字も削除します。

    use Illuminate\Support\Str;

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

// 'Laravel '

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

// 'Laravel/'

rtrim

rtrim メソッドは指定された文字列の右側をトリムします。PHP のネイティブ rtrim 関数とは異なり、Laravel の rtrim メソッドはユニコードの空白文字も削除します。

    use Illuminate\Support\Str;

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

// ' Laravel'

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

// '/Laravel'

ucfirst

ucfirst メソッドは最初の文字を大文字にして指定された文字列を返します。

    use Illuminate\Support\Str;

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

// Foo bar

ucsplit

ucsplit メソッドは大文字の文字で指定された文字列をコレクションに分割します。

    use Illuminate\Support\Str;

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

// collect(['Foo', 'Bar'])

unwrap

unwrap メソッドは指定された文字列を指定された文字列から始まる文字列と終わる文字列を削除します。

    use Illuminate\Support\Str;

Str::of('-Laravel-')->unwrap('-');

// Laravel

Str::of('{framework: "Laravel"}')->unwrap('{', '}');

// framework: "Laravel"

upper

upper メソッドは指定された文字列を大文字に変換します。

    use Illuminate\Support\Str;

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

// LARAVEL

when

when メソッドは指定された条件が true の場合に指定されたクロージャを呼び出します。クロージャは fluent string インスタンスを受け取ります。

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Taylor Otwell'

必要に応じて、when メソッドに第三引数として別のクロージャを渡すことができます。このクロージャは条件パラメータが false に評価された場合に実行されます。

whenContains

whenContains メソッドは文字列が指定された値を含む場合に指定されたクロージャを呼び出します。クロージャは fluent string インスタンスを受け取ります。

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Tony Stark'

必要に応じて、when メソッドの第三引数として別のクロージャを渡すこともできます。このクロージャは、指定された値が含まれていない場合に実行されます。

また、配列を渡して、指定された文字列が配列内のいずれかの値を含んでいるかどうかを判断することもできます:

    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

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'

必要に応じて、when メソッドの第三引数として別のクロージャを渡すこともできます。このクロージャは、条件パラメータが false に評価された場合に実行されます。

whenEmpty

whenEmpty メソッドは、文字列が空の場合に指定されたクロージャを呼び出します。クロージャが値を返す場合、その値は whenEmpty メソッドによって返されます。クロージャが値を返さない場合、フルーエント文字列のインスタンスが返されます:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Laravel'

whenNotEmpty

whenNotEmpty メソッドは、文字列が空でない場合に指定されたクロージャを呼び出します。クロージャが値を返す場合、その値は whenNotEmpty メソッドによって返されます。クロージャが値を返さない場合、フルーエント文字列のインスタンスが返されます:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Laravel Framework'

whenStartsWith

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

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メソッドは、文字列が指定された文字列と完全に一致する場合に、指定されたクロージャを呼び出します。クロージャは、フルート文字列インスタンスを受け取ります:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Laravel'

whenNotExactly

whenNotExactlyメソッドは、文字列が指定された文字列と完全に一致しない場合に、指定されたクロージャを呼び出します。クロージャは、フルート文字列インスタンスを受け取ります:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Framework'

whenIs

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

whenIsAsciiメソッドは、文字列が7ビットASCIIである場合に、指定されたクロージャを呼び出します。クロージャは、フルート文字列インスタンスを受け取ります:

    use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

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

// 'Laravel'

whenIsUlid

whenIsUlidメソッドは、文字列が有効なULIDである場合に、指定されたクロージャを呼び出します。クロージャは、フルート文字列インスタンスを受け取ります:

    use Illuminate\Support\Str;

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

// '01gd6r36'

whenIsUuid

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

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

wordCountメソッドは、文字列が含む単語の数を返します:

use Illuminate\Support\Str;

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

words

wordsメソッドは、文字列内の単語の数を制限します。必要に応じて、切り捨てられた文字列に追加の文字列を指定できます:

    use Illuminate\Support\Str;

$string = Str::of('完璧にバランスが取れています、すべてのものがそうでなければなりません。')->words(3, ' >>>');

// 完璧にバランスが >>>