文字列 (Strings)
導入 (Introduction)
Laravel には、文字列値を操作するためのさまざまな関数が含まれています。これらの関数の多くはフレームワーク自体によって使用されます。ただし、便利だと思われる場合は、独自のアプリケーションで自由に使用できます。
利用可能な方法 (Available Methods)
文字列
__ class_basename e preg_replace_array Str::after Str::afterLast Str::apa Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::charAt Str::chopStart Str::chopEnd Str::contains Str::containsAll Str::doesntContain Str::doesntEndWith Str::doesntStartWith Str::deduplicate Str::endsWith Str::excerpt Str::finish Str::fromBase64 Str::headline Str::initials 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::match Str::matchAll Str::isMatch Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::password Str::plural Str::pluralStudly Str::position Str::random Str::remove Str::repeat Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::replaceMatches Str::replaceStart Str::replaceEnd Str::reverse Str::singular Str::slug Str::snake Str::squish Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::take Str::title Str::toBase64 Str::transliterate Str::trim Str::ltrim Str::rtrim Str::ucfirst Str::ucsplit Str::ucwords Str::upper Str::ulid Str::unwrap Str::uuid Str::uuid7 Str::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
流暢な文字列
after afterLast apa append ascii basename before beforeLast between betweenFirst camel charAt classBasename chopStart chopEnd contains containsAll decrypt deduplicate dirname doesntContain doesntEndWith doesntStartWith encrypt endsWith exactly excerpt explode finish fromBase64 hash headline initials inlineMarkdown is isAscii isEmpty isNotEmpty isJson isUlid isUrl isUuid kebab lcfirst length limit lower markdown mask match matchAll isMatch newLine padBoth padLeft padRight pipe plural position prepend remove repeat replace replaceArray replaceFirst replaceLast replaceMatches replaceStart replaceEnd scan singular slug snake split squish start startsWith stripTags studly substr substrReplace swap take tap test title toBase64 toHtmlString toUri transliterate trim ltrim rtrim ucfirst ucsplit ucwords unwrap upper when whenContains whenContainsAll whenDoesntEndWith whenDoesntStartWith whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words wrap
文字列 (Strings)
__()
__ 関数は、言語ファイル を使用して、指定された翻訳文字列または翻訳キーを翻訳します。
echo __('Welcome to our application');
echo __('messages.welcome');
指定された変換文字列またはキーが存在しない場合、__ 関数は指定された値を返します。したがって、上記の例を使用すると、変換キーが存在しない場合、__ 関数は messages.welcome を返します。
class_basename()
class_basename 関数は、クラスの名前空間が削除された、指定されたクラスのクラス名を返します。
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
e 関数は、デフォルトで double_encode オプションを true に設定して、PHP の htmlspecialchars 関数を実行します。
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::chopStart()
Str::chopStart メソッドは、値が文字列の先頭にある場合にのみ、指定された値の最初の出現を削除します。
use Illuminate\Support\Str;
$url = Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'
2 番目の引数として配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値は文字列から削除されます。
use Illuminate\Support\Str;
$url = Str::chopStart('http://laravel.com', ['https://', 'http://']);
// 'laravel.com'
Str::chopEnd()
Str::chopEnd メソッドは、値が文字列の最後にある場合にのみ、指定された値の最後の出現を削除します。
use Illuminate\Support\Str;
$url = Str::chopEnd('app/Models/Photograph.php', '.php');
// 'app/Models/Photograph'
2 番目の引数として配列を渡すこともできます。文字列が配列内のいずれかの値で終わる場合、その値は文字列から削除されます。
use Illuminate\Support\Str;
$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);
// 'laravel.com'
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
ignoreCase 引数を true に設定することで、大文字と小文字の区別を無効にすることができます。
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'MY', ignoreCase: true);
// true
Str::containsAll()
Str::containsAll メソッドは、指定された文字列に指定された配列内のすべての値が含まれているかどうかを判断します。
use Illuminate\Support\Str;
$containsAll = Str::containsAll('This is my name', ['my', 'name']);
// true
ignoreCase 引数を true に設定することで、大文字と小文字の区別を無効にすることができます。
use Illuminate\Support\Str;
$containsAll = Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true);
// true
Str::doesntContain()
Str::doesntContain メソッドは、指定された文字列に指定された値が含まれていないかどうかを判断します。デフォルトでは、このメソッドは大文字と小文字が区別されます。
use Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', 'my');
// true
値の配列を渡して、指定された文字列に配列内の値が含まれていないかどうかを確認することもできます。
use Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', ['my', 'framework']);
// true
ignoreCase 引数を true に設定することで、大文字と小文字の区別を無効にすることができます。
use Illuminate\Support\Str;
$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true);
// true
Str::deduplicate()
Str::deduplicate メソッドは、指定された文字列内の文字の連続したインスタンスをその文字の単一のインスタンスに置き換えます。デフォルトでは、このメソッドはスペースを重複排除します。
use Illuminate\Support\Str;
$result = Str::deduplicate('The Laravel Framework');
// The Laravel Framework
重複排除する別の文字を指定するには、それをメソッドの 2 番目の引数として渡します。
use Illuminate\Support\Str;
$result = Str::deduplicate('The---Laravel---Framework', '-');
// The-Laravel-Framework
Str::doesntEndWith()
Str::doesntEndWith メソッドは、指定された文字列が指定された値で終わっていないかどうかを判断します。
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', 'dog');
// true
値の配列を渡して、指定された文字列が配列内のどの値でも終わっていないかどうかを判断することもできます。
use Illuminate\Support\Str;
$result = Str::doesntEndWith('This is my name', ['this', 'foo']);
// true
$result = Str::doesntEndWith('This is my name', ['name', 'foo']);
// false
Str::doesntStartWith()
Str::doesntStartWith メソッドは、指定された文字列が指定された値で始まらないかどうかを判断します。
use Illuminate\Support\Str;
$result = Str::doesntStartWith('This is my name', 'That');
// true
可能な値の配列が渡された場合、文字列が指定された値のいずれでも始まらない場合、doesntStartWith メソッドは true を返します。
$result = Str::doesntStartWith('This is my name', ['What', 'That', 'There']);
// 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::fromBase64()
Str::fromBase64 メソッドは、指定された Base64 文字列をデコードします。
use Illuminate\Support\Str;
$decoded = Str::fromBase64('TGFyYXZlbA==');
// Laravel
Str::headline()
Str::headline メソッドは、大文字と小文字、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字が大文字になったスペースで区切られた文字列に変換します。
use Illuminate\Support\Str;
$headline = Str::headline('steve_jobs');
// Steve Jobs
$headline = Str::headline('EmailNotificationSent');
// Email Notification Sent
Str::initials()
Str::initials メソッドは、指定された文字列のイニシャルを返します。オプションで大文字にすることもできます。
use Illuminate\Support\Str;
$initials = Str::initials('taylor otwell');
// to
$initials = Str::initials('taylor otwell', capitalize: true);
// TO
Str::inlineMarkdown()
Str::inlineMarkdown メソッドは、CommonMark を使用して、GitHub フレーバーの Markdown をインライン HTML に変換します。ただし、markdown メソッドとは異なり、生成されたすべての HTML をブロックレベル要素でラップするわけではありません。
use Illuminate\Support\Str;
$html = Str::inlineMarkdown('**Laravel**');
// <strong>Laravel</strong>
マークダウンセキュリティ
デフォルトでは、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
ignoreCase 引数を true に設定することで、大文字と小文字の区別を無効にすることができます。
use Illuminate\Support\Str;
$matches = Str::is('*.jpg', 'photo.JPG', ignoreCase: true);
// true
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
指定された UUID がバージョン (1、3、4、5、6、7、または 8) ごとの UUID 仕様と一致することを検証することもできます。
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4);
// true
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1);
// false
Str::kebab()
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...
メソッドに 3 番目の引数を渡して、切り詰められた文字列の末尾に追加される文字列を変更できます。
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)
文字列を切り詰めるときに完全な単語を保持したい場合は、preserveWords 引数を利用できます。この引数が true の場合、文字列は最も近い完全な単語境界まで切り詰められます。
$truncated = Str::limit('The quick brown fox', 12, preserveWords: true);
// The quick...
Str::lower()
Str::lower メソッドは、指定された文字列を小文字に変換します。
use Illuminate\Support\Str;
$converted = Str::lower('LARAVEL');
// laravel
Str::markdown()
Str::markdown メソッドは、CommonMark を使用して、GitHub フレーバーの Markdown を HTML に変換します。
use Illuminate\Support\Str;
$html = Str::markdown('# Laravel');
// <h1>Laravel</h1>
$html = Str::markdown('# Taylor <b>Otwell</b>', [
'html_input' => 'strip',
]);
// <h1>Taylor Otwell</h1>
マークダウンセキュリティ
デフォルトでは、Markdown は生の 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;
// tay***************
必要に応じて、mask メソッドの 3 番目の引数として負の数値を指定します。これにより、文字列の末尾から指定された距離でマスクを開始するようにメソッドに指示されます。
// tay***@example.com
Str::match()
Str::match メソッドは、指定された正規表現パターンに一致する文字列の部分を返します。
use Illuminate\Support\Str;
$result = Str::match('/bar/', 'foo bar');
// 'bar'
$result = Str::match('/foo (.*)/', 'foo bar');
// 'bar'
Str::matchAll()
Str::matchAll メソッドは、指定された正規表現パターンに一致する文字列の部分を含むコレクションを返します。
use Illuminate\Support\Str;
$result = Str::matchAll('/bar/', 'bar foo bar');
// collect(['bar', 'bar'])
式内で一致するグループを指定すると、Laravel は最初に一致したグループの一致のコレクションを返します。
use Illuminate\Support\Str;
$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly');
// collect(['un', 'ly']);
一致するものが見つからない場合は、空のコレクションが返されます。
Str::isMatch()
文字列が指定された正規表現に一致する場合、Str::isMatch メソッドは true を返します。
use Illuminate\Support\Str;
$result = Str::isMatch('/foo (.*)/', 'foo bar');
// true
$result = Str::isMatch('/foo (.*)/', 'laravel');
// false
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のpluralizerでサポートされている言語のいずれか をサポートします。
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
prependCount 引数を指定すると、書式設定された $count を複数化された文字列の前に付けることができます。
use Illuminate\Support\Str;
$label = Str::plural('car', 1000, prependCount: true);
// 1,000 cars
Str::pluralStudly()
Str::pluralStudly メソッドは、大文字小文字でフォーマットされた単数形の単語文字列を複数形に変換します。この関数は Laravelのpluralizerでサポートされている言語のいずれか をサポートします。
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.
文字列を削除するときに大文字と小文字を区別しないように、false を remove メソッドの 3 番目の引数として渡すこともできます。
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 11.x';
$replaced = Str::replace('11.x', '12.x', $string);
// Laravel 12.x
replace メソッドは、caseSensitive 引数も受け入れます。デフォルトでは、replace メソッドでは大文字と小文字が区別されます。
$replaced = Str::replace(
'php',
'Laravel',
'PHP Framework for Web Artisans',
caseSensitive: false
);
// Laravel Framework for Web Artisans
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のpluralizerでサポートされている言語のいずれか をサポートします。
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 メソッドは、start パラメーターと length パラメーターで指定された文字列の部分を返します。
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 メソッドは、文字列の一部内のテキストを、3 番目の引数で指定された位置から開始して 4 番目の引数で指定された文字数まで置き換えます。 0 をメソッドの 4 番目の引数に渡すと、文字列内の既存の文字を置換せずに、指定された位置に文字列が挿入されます。
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::transliterate()
Str::transliterate メソッドは、指定された文字列を最も近い ASCII 表現に変換しようとします。
use Illuminate\Support\Str;
$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
// '[email protected]'
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::ucwords()
Str::ucwords メソッドは、指定された文字列内の各単語の最初の文字を大文字に変換します。
use Illuminate\Support\Str;
$string = Str::ucwords('laravel framework');
// Laravel Framework
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::uuid7()
Str::uuid7 メソッドは UUID (バージョン 7) を生成します。
use Illuminate\Support\Str;
return (string) Str::uuid7();
DateTimeInterface は、順序付けされた UUID の生成に使用されるオプションのパラメーターとして渡すことができます。
return (string) Str::uuid7(time: now());
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 メソッドは、文字列内の単語数を制限します。追加の文字列を 3 番目の引数を介してこのメソッドに渡し、切り詰められた文字列の末尾に追加する文字列を指定できます。
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 を返します。
流暢な文字列 (Fluent Strings)
Fluent String は、文字列値を操作するためのより流暢なオブジェクト指向インターフェイスを提供し、従来の文字列操作と比較して読みやすい構文を使用して複数の文字列操作を連鎖させることができます。
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'
chopStart
chopStart メソッドは、値が文字列の先頭にある場合にのみ、指定された値の最初の出現を削除します。
use Illuminate\Support\Str;
$url = Str::of('https://laravel.com')->chopStart('https://');
// 'laravel.com'
配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値は文字列から削除されます。
use Illuminate\Support\Str;
$url = Str::of('http://laravel.com')->chopStart(['https://', 'http://']);
// 'laravel.com'
chopEnd
chopEnd メソッドは、値が文字列の最後にある場合にのみ、指定された値の最後の出現を削除します。
use Illuminate\Support\Str;
$url = Str::of('https://laravel.com')->chopEnd('.com');
// 'https://laravel'
配列を渡すこともできます。文字列が配列内のいずれかの値で終わる場合、その値は文字列から削除されます。
use Illuminate\Support\Str;
$url = Str::of('http://laravel.com')->chopEnd(['.com', '.io']);
// 'http://laravel'
contains
contains メソッドは、指定された文字列に指定された値が含まれているかどうかを判断します。デフォルトでは、このメソッドは大文字と小文字が区別されます。
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains('my');
// true
値の配列を渡して、指定された文字列に配列内の値が含まれているかどうかを確認することもできます。
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains(['my', 'foo']);
// true
大文字と小文字の区別を無効にするには、ignoreCase 引数を true に設定します。
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains('MY', ignoreCase: true);
// true
containsAll
containsAll メソッドは、指定された文字列に指定された配列内のすべての値が含まれているかどうかを判断します。
use Illuminate\Support\Str;
$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);
// true
大文字と小文字の区別を無効にするには、ignoreCase 引数を true に設定します。
use Illuminate\Support\Str;
$containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);
// true
decrypt
decrypt メソッド decrypts 暗号化された文字列:
use Illuminate\Support\Str;
$decrypted = $encrypted->decrypt();
// 'secret'
decrypt の逆については、encrypt メソッドを参照してください。
deduplicate
deduplicate メソッドは、指定された文字列内の文字の連続したインスタンスをその文字の単一のインスタンスに置き換えます。デフォルトでは、このメソッドはスペースを重複排除します。
use Illuminate\Support\Str;
$result = Str::of('The Laravel Framework')->deduplicate();
// The Laravel Framework
重複排除する別の文字を指定するには、それをメソッドの 2 番目の引数として渡します。
use Illuminate\Support\Str;
$result = Str::of('The---Laravel---Framework')->deduplicate('-');
// The-Laravel-Framework
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'
doesntContain()
doesntContain メソッドは、指定された文字列に指定された値が含まれていないかどうかを判断します。このメソッドは、contains メソッドの逆です。デフォルトでは、このメソッドは大文字と小文字が区別されます。
use Illuminate\Support\Str;
$doesntContain = Str::of('This is name')->doesntContain('my');
// true
値の配列を渡して、指定された文字列に配列内の値が含まれていないかどうかを確認することもできます。
use Illuminate\Support\Str;
$doesntContain = Str::of('This is name')->doesntContain(['my', 'framework']);
// true
ignoreCase 引数を true に設定することで、大文字と小文字の区別を無効にすることができます。
use Illuminate\Support\Str;
$doesntContain = Str::of('This is my name')->doesntContain('MY', ignoreCase: true);
// false
doesntEndWith
doesntEndWith メソッドは、指定された文字列が指定された値で終わっていないかどうかを判断します。
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith('dog');
// true
値の配列を渡して、指定された文字列が配列内のどの値でも終わっていないかどうかを判断することもできます。
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntEndWith(['this', 'foo']);
// true
$result = Str::of('This is my name')->doesntEndWith(['name', 'foo']);
// false
doesntStartWith
doesntStartWith メソッドは、指定された文字列が指定された値で始まらないかどうかを判断します。
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith('That');
// true
値の配列を渡して、指定された文字列が配列内のどの値でも始まらないかどうかを判断することもできます。
use Illuminate\Support\Str;
$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);
// true
encrypt
encrypt メソッド encrypts 文字列:
use Illuminate\Support\Str;
$encrypted = Str::of('secret')->encrypt();
encrypt の逆については、decrypt メソッドを参照してください。
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
excerpt
excerpt メソッドは、文字列内のフレーズの最初のインスタンスに一致する文字列からの抜粋を抽出します。
use Illuminate\Support\Str;
$excerpt = Str::of('This is my name')->excerpt('my', [
'radius' => 3
]);
// '...is my na...'
radius オプション (デフォルトは 100) を使用すると、切り詰められた文字列の両側に表示される文字数を定義できます。
さらに、omission オプションを使用して、切り詰められた文字列の前後に追加される文字列を変更することもできます。
use Illuminate\Support\Str;
$excerpt = Str::of('This is my name')->excerpt('name', [
'radius' => 3,
'omission' => '(...) '
]);
// '(...) my name'
explode
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/
fromBase64
fromBase64 メソッドは、指定された Base64 文字列をデコードします。
use Illuminate\Support\Str;
$decoded = Str::of('TGFyYXZlbA==')->fromBase64();
// Laravel
hash
hash メソッドは、指定された algorithm を使用して文字列をハッシュします。
use Illuminate\Support\Str;
$hashed = Str::of('secret')->hash(algorithm: 'sha256');
// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'
headline
headline メソッドは、大文字と小文字、ハイフン、またはアンダースコアで区切られた文字列を、各単語の最初の文字が大文字になったスペースで区切られた文字列に変換します。
use Illuminate\Support\Str;
$headline = Str::of('taylor_otwell')->headline();
// Taylor Otwell
$headline = Str::of('EmailNotificationSent')->headline();
// Email Notification Sent
initials
initials メソッドは文字列をそのイニシャルに変換します。
use Illuminate\Support\Str;
$initials = Str::of('Taylor Otwell')->initials()->upper();
// TO
inlineMarkdown
inlineMarkdown メソッドは、CommonMark を使用して、GitHub フレーバーの Markdown をインライン HTML に変換します。ただし、markdown メソッドとは異なり、生成されたすべての HTML をブロックレベル要素でラップするわけではありません。
use Illuminate\Support\Str;
$html = Str::of('**Laravel**')->inlineMarkdown();
// <strong>Laravel</strong>
マークダウンセキュリティ
デフォルトでは、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
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
指定された UUID がバージョン (1、3、4、5、6、7、または 8) ごとの UUID 仕様と一致することを検証することもできます。
use Illuminate\Support\Str;
$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4);
// true
$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1);
// false
kebab
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
limit メソッドは、指定された文字列を指定された長さに切り詰めます。
use Illuminate\Support\Str;
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox...
2 番目の引数を渡して、切り詰められた文字列の末尾に追加される文字列を変更することもできます。
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)
文字列を切り詰めるときに完全な単語を保持したい場合は、preserveWords 引数を利用できます。この引数が true の場合、文字列は最も近い完全な単語境界まで切り詰められます。
$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true);
// The quick...
lower
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 は生の 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
mask メソッドは、文字列の一部を繰り返し文字でマスクし、電子メール アドレスや電話番号などの文字列のセグメントを難読化するために使用できます。
use Illuminate\Support\Str;
// tay***************
必要に応じて、mask メソッドの 3 番目または 4 番目の引数として負の数値を指定できます。これにより、文字列の末尾から指定された距離でマスクを開始するようにメソッドに指示されます。
// tay***@example.com
// 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 メソッドを使用すると、現在の値を指定された呼び出し可能オブジェクトに渡すことで文字列を変換できます。
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のpluralizerでサポートされている言語のいずれか をサポートします。
use Illuminate\Support\Str;
$plural = Str::of('car')->plural();
// cars
$plural = Str::of('child')->plural();
// children
関数に整数の引数を指定して、文字列の単数形または複数形を取得できます。
use Illuminate\Support\Str;
$plural = Str::of('child')->plural(2);
// children
$plural = Str::of('child')->plural(1);
// child
prependCount 引数を指定して、書式設定された $count を複数化された文字列の前に付けることができます。
use Illuminate\Support\Str;
$label = Str::of('car')->plural(1000, prependCount: true);
// 1,000 cars
position
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
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のpluralizerでサポートされている言語のいずれか をサポートします。
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
値の配列を渡して、指定された文字列が配列内のいずれかの値で始まるかどうかを判断することもできます。
use Illuminate\Support\Str;
$result = Str::of('This is my name')->startsWith(['This', 'That']);
// true
stripTags
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 メソッドは、指定された start パラメーターと length パラメーターで指定された文字列の部分を返します。
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 番目の引数で指定された文字数まで置き換えます。 0 をメソッドの 3 番目の引数に渡すと、文字列内の既存の文字を置換せずに、指定された位置に文字列が挿入されます。
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==
toHtmlString
toHtmlString メソッドは、指定された文字列を Illuminate\Support\HtmlString のインスタンスに変換します。これは、Blade テンプレートでレンダリングされるときにエスケープされません。
use Illuminate\Support\Str;
$htmlString = Str::of('Nuno Maduro')->toHtmlString();
toUri
toUri メソッドは、指定された文字列を Illuminate\Support\Uri のインスタンスに変換します。
use Illuminate\Support\Str;
$uri = Str::of('https://example.com')->toUri();
transliterate
transliterate メソッドは、指定された文字列を最も近い ASCII 表現に変換しようとします。
use Illuminate\Support\Str;
$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate()
// '[email protected]'
trim
trim メソッドは、指定された文字列をトリミングします。 PHP のネイティブ trim 関数とは異なり、Laravel の trim メソッドは Unicode 空白文字も削除します。
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->trim();
// 'Laravel'
$string = Str::of('/Laravel/')->trim('/');
// 'Laravel'
ltrim
ltrim メソッドは、文字列の左側をトリミングします。 PHP のネイティブ ltrim 関数とは異なり、Laravel の ltrim メソッドは Unicode 空白文字も削除します。
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->ltrim();
// 'Laravel '
$string = Str::of('/Laravel/')->ltrim('/');
// 'Laravel/'
rtrim
rtrim メソッドは、指定された文字列の右側をトリミングします。 PHP のネイティブ rtrim 関数とは異なり、Laravel の rtrim メソッドは Unicode 空白文字も削除します。
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'])
ucwords
ucwords メソッドは、指定された文字列内の各単語の最初の文字を大文字に変換します。
use Illuminate\Support\Str;
$string = Str::of('laravel framework')->ucwords();
// Laravel Framework
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 の場合、指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('Taylor')
->when(true, function (Stringable $string) {
return $string->append(' Otwell');
});
// 'Taylor Otwell'
必要に応じて、別のクロージャを 3 番目のパラメータとして when メソッドに渡すことができます。このクロージャは、条件パラメータが false と評価された場合に実行されます。
whenContains
whenContains メソッドは、文字列に指定された値が含まれている場合に、指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('tony stark')
->whenContains('tony', function (Stringable $string) {
return $string->title();
});
// 'Tony Stark'
必要に応じて、別のクロージャを 3 番目のパラメータとして渡すことができます。文字列に指定された値が含まれていない場合、クロージャが呼び出されます。
値の配列を渡して、指定された文字列に配列内の値が含まれているかどうかを確認することもできます。
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'
必要に応じて、別のクロージャを 3 番目のパラメータとして渡すことができます。条件パラメータが false と評価された場合、クロージャが呼び出されます。
whenDoesntEndWith
whenDoesntEndWith メソッドは、文字列が指定された部分文字列で終わっていない場合に、指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) {
return $string->title();
});
// 'Disney World'
whenDoesntStartWith
whenDoesntStartWith メソッドは、文字列が指定された部分文字列で始まらない場合に、指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
return $string->title();
});
// 'Disney World'
whenEmpty
whenEmpty メソッドは、文字列が空の場合、指定されたクロージャを呼び出します。クロージャが値を返す場合、その値は whenEmpty メソッドによっても返されます。クロージャが値を返さない場合は、流暢な文字列インスタンスが返されます。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of(' ')->trim()->whenEmpty(function (Stringable $string) {
return $string->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
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
文字列が 7 ビット ASCII の場合、whenIsAscii メソッドは指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
return $string->title();
});
// 'Laravel'
whenIsUlid
文字列が有効な ULID の場合、whenIsUlid メソッドは指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
use Illuminate\Support\Str;
$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
return $string->substr(0, 8);
});
// '01gd6r36'
whenIsUuid
文字列が有効な UUID の場合、whenIsUuid メソッドは指定されたクロージャを呼び出します。クロージャは流暢な文字列インスタンスを受け取ります。
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('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Perfectly balanced, as >>>
wrap
wrap メソッドは、指定された文字列を追加の文字列または文字列のペアでラップします。
use Illuminate\Support\Str;
Str::of('Laravel')->wrap('"');
// "Laravel"
Str::is('is')->wrap(before: 'This ', after: ' Laravel!');
// This is Laravel!