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