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