文字列
はじめに
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>');
// <html>foo</html>
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("Hello XSS!");
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("Hello XSS!");</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"