コンテンツへスキップ

文字列

はじめに

Laravelは、文字列値を操作するためのさまざまな関数を備えています。これらの関数の多くはフレームワーク自体で使用されていますが、必要に応じて独自のアプリケーションで使用できます。

利用可能なメソッド

文字列

Fluent Strings

文字列

__()

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

echo __('Welcome to our application');
 
echo __('messages.welcome');

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

class_basename()

class_basename関数は、クラスのネームスペースを除去した、指定されたクラスのクラス名を返します。

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

e()

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

echo e('<html>foo</html>');
 
// &lt;html&gt;foo&lt;/html&gt;

preg_replace_array()

preg_replace_array関数は、配列を使用して文字列内の指定されたパターンを順番に置換します。

$string = 'The event will take place between :start and :end';
 
$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);
 
// The event will take place between 8:30 and 9:00

Str::after()

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

use Illuminate\Support\Str;
 
$slice = Str::after('This is my name', 'This is');
 
// ' my name'

Str::afterLast()

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

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

Str::apa()

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

use Illuminate\Support\Str;
 
$title = Str::apa('Creating A Project');
 
// 'Creating a Project'

Str::ascii()

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

use Illuminate\Support\Str;
 
$slice = Str::ascii('û');
 
// 'u'

Str::before()

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

use Illuminate\Support\Str;
 
$slice = Str::before('This is my name', 'my name');
 
// 'This is '

Str::beforeLast()

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

use Illuminate\Support\Str;
 
$slice = Str::beforeLast('This is my name', 'is');
 
// 'This '

Str::between()

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

use Illuminate\Support\Str;
 
$slice = Str::between('This is my name', 'This', 'name');
 
// ' is my '

Str::betweenFirst()

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

use Illuminate\Support\Str;
 
$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
 
// 'a'

Str::camel()

Str::camel メソッドは、与えられた文字列をcamelCaseに変換します。

use Illuminate\Support\Str;
 
$converted = Str::camel('foo_bar');
 
// 'fooBar'

Str::charAt()

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

use Illuminate\Support\Str;
 
$character = Str::charAt('This is my name.', 6);
 
// 's'

Str::chopStart()

Str::chopStart メソッドは、指定された値が文字列の先頭にある場合のみ、その値の最初の出現を削除します。

use Illuminate\Support\Str;
 
$url = Str::chopStart('https://laravel.dokyumento.jp', 'https://');
 
// 'laravel.com'

第2引数として配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値は文字列から削除されます。

use Illuminate\Support\Str;
 
$url = Str::chopStart('https://laravel.dokyumento.jp', ['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', 'foo']);
 
// 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::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...'

デフォルト値が100であるradiusオプションを使用すると、切り詰められた文字列の各側に表示される文字数を定義できます。

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

use Illuminate\Support\Str;
 
$html = Str::inlineMarkdown('**Laravel**');
 
// <strong>Laravel</strong>

Markdownのセキュリティ

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

use Illuminate\Support\Str;
 
Str::inlineMarkdown('Inject: <script>alert("Hello XSS!");</script>', [
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
 
// Inject: alert(&quot;Hello XSS!&quot;);

Str::is()

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

use Illuminate\Support\Str;
 
$matches = Str::is('foo*', 'foobar');
 
// true
 
$matches = Str::is('baz*', 'foobar');
 
// false

Str::isAscii()

Str::isAscii メソッドは、与えられた文字列が7ビットASCIIかどうかを判定します。

use Illuminate\Support\Str;
 
$isAscii = Str::isAscii('Taylor');
 
// true
 
$isAscii = Str::isAscii('ü');
 
// false

Str::isJson()

Str::isJson メソッドは、与えられた文字列が有効なJSONかどうかを判定します。

use Illuminate\Support\Str;
 
$result = Str::isJson('[1,2,3]');
 
// true
 
$result = Str::isJson('{"first": "John", "last": "Doe"}');
 
// true
 
$result = Str::isJson('{first: "John", last: "Doe"}');
 
// false

Str::isUrl()

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

use Illuminate\Support\Str;
 
$isUrl = Str::isUrl('http://example.com');
 
// true
 
$isUrl = Str::isUrl('laravel');
 
// false

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

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

Str::isUlid()

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

use Illuminate\Support\Str;
 
$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
 
// true
 
$isUlid = Str::isUlid('laravel');
 
// false

Str::isUuid()

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

use Illuminate\Support\Str;
 
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
 
// true
 
$isUuid = Str::isUuid('laravel');
 
// false

Str::kebab()

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

use Illuminate\Support\Str;
 
$converted = Str::kebab('fooBar');
 
// foo-bar

Str::lcfirst()

Str::lcfirst メソッドは、最初の文字を小文字にした与えられた文字列を返します。

use Illuminate\Support\Str;
 
$string = Str::lcfirst('Foo Bar');
 
// foo Bar

Str::length()

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

use Illuminate\Support\Str;
 
$length = Str::length('Laravel');
 
// 7

Str::limit()

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

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

メソッドに第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のセキュリティ

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

use Illuminate\Support\Str;
 
Str::markdown('Inject: <script>alert("Hello XSS!");</script>', [
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
 
// <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

Str::mask()

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

use Illuminate\Support\Str;
 
$string = Str::mask('[email protected]', '*', 3);
 
// tay***************

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

$string = Str::mask('[email protected]', '*', -15, 3);
 
// tay***@example.com

Str::orderedUuid()

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

use Illuminate\Support\Str;
 
return (string) Str::orderedUuid();

Str::padBoth()

Str::padBoth メソッドはPHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の両側に別の文字列をパディングします。

use Illuminate\Support\Str;
 
$padded = Str::padBoth('James', 10, '_');
 
// '__James___'
 
$padded = Str::padBoth('James', 10);
 
// ' James '

Str::padLeft()

Str::padLeft メソッドはPHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の左側に別の文字列をパディングします。

use Illuminate\Support\Str;
 
$padded = Str::padLeft('James', 10, '-=');
 
// '-=-=-James'
 
$padded = Str::padLeft('James', 10);
 
// ' James'

Str::padRight()

Str::padRight メソッドはPHPのstr_pad関数をラップし、最終的な文字列が目的の長さに達するまで、文字列の右側に別の文字列をパディングします。

use Illuminate\Support\Str;
 
$padded = Str::padRight('James', 10, '-');
 
// 'James-----'
 
$padded = Str::padRight('James', 10);
 
// 'James '

Str::password()

Str::password メソッドは、指定された長さの安全なランダムパスワードを生成するために使用できます。パスワードは、文字、数字、記号、スペースの組み合わせで構成されます。デフォルトでは、パスワードは32文字の長さです。

use Illuminate\Support\Str;
 
$password = Str::password();
 
// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'
 
$password = Str::password(12);
 
// 'qwuar>#V|i]N'

Str::plural()

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

use Illuminate\Support\Str;
 
$plural = Str::plural('car');
 
// cars
 
$plural = Str::plural('child');
 
// children

関数の第2引数として整数を指定して、文字列の単数形または複数形を取得できます。

use Illuminate\Support\Str;
 
$plural = Str::plural('child', 2);
 
// children
 
$singular = Str::plural('child', 1);
 
// child

Str::pluralStudly()

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

use Illuminate\Support\Str;
 
$plural = Str::pluralStudly('VerifiedHuman');
 
// VerifiedHumans
 
$plural = Str::pluralStudly('UserFeedback');
 
// UserFeedback

関数の第2引数として整数を指定して、文字列の単数形または複数形を取得できます。

use Illuminate\Support\Str;
 
$plural = Str::pluralStudly('VerifiedHuman', 2);
 
// VerifiedHumans
 
$singular = Str::pluralStudly('VerifiedHuman', 1);
 
// VerifiedHuman

Str::position()

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

use Illuminate\Support\Str;
 
$position = Str::position('Hello, World!', 'Hello');
 
// 0
 
$position = Str::position('Hello, World!', 'W');
 
// 7

Str::random()

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

use Illuminate\Support\Str;
 
$random = Str::random(40);

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

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

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

Str::createRandomStringsNormally();

Str::remove()

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

use Illuminate\Support\Str;
 
$string = 'Peter Piper picked a peck of pickled peppers.';
 
$removed = Str::remove('e', $string);
 
// Ptr Pipr pickd a pck of pickld ppprs.

removeメソッドの第3引数としてfalseを渡して、文字列を削除する際に大文字と小文字を無視することもできます。

Str::repeat()

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

use Illuminate\Support\Str;
 
$string = 'a';
 
$repeat = Str::repeat($string, 5);
 
// aaaaa

Str::replace()

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

use Illuminate\Support\Str;
 
$string = 'Laravel 10.x';
 
$replaced = Str::replace('10.x', '11.x', $string);
 
// Laravel 11.x

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

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

Str::replaceArray()

Str::replaceArray メソッドは、配列を使用して文字列内の指定された値を順番に置き換えます。

use Illuminate\Support\Str;
 
$string = 'The event will take place between ? and ?';
 
$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
 
// The event will take place between 8:30 and 9:00

Str::replaceFirst()

Str::replaceFirst メソッドは、文字列内の指定された値の最初の出現を置き換えます。

use Illuminate\Support\Str;
 
$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
 
// a quick brown fox jumps over the lazy dog

Str::replaceLast()

Str::replaceLast メソッドは、文字列内の指定された値の最後の出現を置き換えます。

use Illuminate\Support\Str;
 
$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
 
// the quick brown fox jumps over a lazy dog

Str::replaceMatches()

Str::replaceMatches メソッドは、パターンに一致する文字列のすべての部分を、指定された置換文字列で置き換えます。

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

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

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

Str::replaceStart()

Str::replaceStart メソッドは、指定された値が文字列の先頭にある場合のみ、その値の最初の出現を置き換えます。

use Illuminate\Support\Str;
 
$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');
 
// Laravel World
 
$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');
 
// Hello World

Str::replaceEnd()

Str::replaceEnd メソッドは、指定された値が文字列の末尾にある場合のみ、その値の最後の出現を置き換えます。

use Illuminate\Support\Str;
 
$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World');
 
// Hello Laravel
 
$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World');
 
// Hello World

Str::reverse()

Str::reverse メソッドは、与えられた文字列を反転します。

use Illuminate\Support\Str;
 
$reversed = Str::reverse('Hello World');
 
// dlroW olleH

Str::singular()

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

use Illuminate\Support\Str;
 
$singular = Str::singular('cars');
 
// car
 
$singular = Str::singular('children');
 
// child

Str::slug()

Str::slug メソッドは、与えられた文字列からURLフレンドリーな「slug」を生成します。

use Illuminate\Support\Str;
 
$slug = Str::slug('Laravel 5 Framework', '-');
 
// laravel-5-framework

Str::snake()

Str::snake メソッドは、与えられた文字列をsnake_caseに変換します。

use Illuminate\Support\Str;
 
$converted = Str::snake('fooBar');
 
// foo_bar
 
$converted = Str::snake('fooBar', '-');
 
// foo-bar

Str::squish()

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

use Illuminate\Support\Str;
 
$string = Str::squish(' laravel framework ');
 
// laravel framework

Str::start()

Str::start メソッドは、指定された値が既に文字列の先頭にある場合、その値の単一のインスタンスを文字列に追加します。

use Illuminate\Support\Str;
 
$adjusted = Str::start('this/string', '/');
 
// /this/string
 
$adjusted = Str::start('/this/string', '/');
 
// /this/string

Str::startsWith()

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

use Illuminate\Support\Str;
 
$result = Str::startsWith('This is my name', 'This');
 
// true

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

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

Str::studly()

Str::studly メソッドは、与えられた文字列をStudlyCaseに変換します。

use Illuminate\Support\Str;
 
$converted = Str::studly('foo_bar');
 
// FooBar

Str::substr()

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

use Illuminate\Support\Str;
 
$converted = Str::substr('The Laravel Framework', 4, 7);
 
// Laravel

Str::substrCount()

Str::substrCount メソッドは、与えられた文字列内に与えられた値が出現する回数を返します。

use Illuminate\Support\Str;
 
$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
 
// 2

Str::substrReplace()

Str::substrReplaceメソッドは、文字列の一部にあるテキストを置換します。3番目の引数で指定された位置から開始し、4番目の引数で指定された数の文字を置換します。メソッドの4番目の引数に0を渡すと、既存の文字を置換せずに、指定された位置に文字列を挿入します。

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

Str::swap()

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

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

Str::take()

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

use Illuminate\Support\Str;
 
$taken = Str::take('Build something amazing!', 5);
 
// Build

Str::title()

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

use Illuminate\Support\Str;
 
$converted = Str::title('a nice title uses the correct case');
 
// A Nice Title Uses The Correct Case

Str::toBase64()

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

use Illuminate\Support\Str;
 
$base64 = Str::toBase64('Laravel');
 
// TGFyYXZlbA==

Str::toHtmlString()

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

use Illuminate\Support\Str;
 
$htmlString = Str::of('Nuno Maduro')->toHtmlString();

Str::transliterate()

Str::transliterateメソッドは、指定された文字列を最も近いASCII表現に変換しようとします。

use Illuminate\Support\Str;
 
$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
 

Str::trim()

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

use Illuminate\Support\Str;
 
$string = Str::trim(' foo bar ');
 
// 'foo bar'

Str::ltrim()

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

use Illuminate\Support\Str;
 
$string = Str::ltrim(' foo bar ');
 
// 'foo bar '

Str::rtrim()

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

use Illuminate\Support\Str;
 
$string = Str::rtrim(' foo bar ');
 
// ' foo bar'

Str::ucfirst()

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

use Illuminate\Support\Str;
 
$string = Str::ucfirst('foo bar');
 
// Foo bar

Str::ucsplit()

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

use Illuminate\Support\Str;
 
$segments = Str::ucsplit('FooBar');
 
// [0 => 'Foo', 1 => 'Bar']

Str::upper()

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

use Illuminate\Support\Str;
 
$string = Str::upper('laravel');
 
// LARAVEL

Str::ulid()

Str::ulidメソッドは、コンパクトで時間順序付けされた一意の識別子であるULIDを生成します。

use Illuminate\Support\Str;
 
return (string) Str::ulid();
 
// 01gd6r360bp37zj17nxb55yv40

指定されたULIDが作成された日時を表すIlluminate\Support\Carbon日付インスタンスを取得する場合は、LaravelのCarbon統合によって提供されるcreateFromIdメソッドを使用できます。

use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
 
$date = Carbon::createFromId((string) Str::ulid());

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

use Symfony\Component\Uid\Ulid;
 
Str::createUlidsUsing(function () {
return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});

ulidメソッドに通常どおりULIDを生成するように指示するには、createUlidsNormallyメソッドを呼び出します。

Str::createUlidsNormally();

Str::unwrap()

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

use Illuminate\Support\Str;
 
Str::unwrap('-Laravel-', '-');
 
// Laravel
 
Str::unwrap('{framework: "Laravel"}', '{', '}');
 
// framework: "Laravel"

Str::uuid()

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

use Illuminate\Support\Str;
 
return (string) Str::uuid();

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

use Ramsey\Uuid\Uuid;
 
Str::createUuidsUsing(function () {
return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');
});

uuidメソッドに通常どおりUUIDを生成するように指示するには、createUuidsNormallyメソッドを呼び出します。

Str::createUuidsNormally();

Str::wordCount()

Str::wordCountメソッドは、文字列に含まれる単語数を返します。

use Illuminate\Support\Str;
 
Str::wordCount('Hello, world!'); // 2

Str::wordWrap()

Str::wordWrapメソッドは、文字列を指定された文字数に折り返します。

use Illuminate\Support\Str;
 
$text = "The quick brown fox jumped over the lazy dog."
 
Str::wordWrap($text, characters: 20, break: "<br />\n");
 
/*
The quick brown fox<br />
jumped over the lazy<br />
dog.
*/

Str::words()

Str::wordsメソッドは、文字列内の単語数を制限します。切り詰められた文字列の末尾に付ける文字列を指定するには、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 stringsは、文字列値を操作するためのより流暢でオブジェクト指向のインターフェースを提供します。従来の文字列操作と比較して、より読みやすい構文を使用して複数の文字列操作をチェーンできます。

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.dokyumento.jp')->chopStart('https://');
 
// 'laravel.com'

配列を渡すこともできます。文字列が配列内のいずれかの値で始まる場合、その値は文字列から削除されます。

use Illuminate\Support\Str;
 
$url = Str::of('https://laravel.dokyumento.jp')->chopStart(['https://', 'http://']);
 
// 'laravel.com'

chopEnd

chopEndメソッドは、指定された値が文字列の末尾に現れる場合のみ、その値の最後の出現箇所を削除します。

use Illuminate\Support\Str;
 
$url = Str::of('https://laravel.dokyumento.jp')->chopEnd('.com');
 
// 'https://laravel'

配列を渡すこともできます。文字列が配列内のいずれかの値で終わる場合、その値は文字列から削除されます。

use Illuminate\Support\Str;
 
$url = Str::of('https://laravel.dokyumento.jp')->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...'

デフォルト値が100であるradiusオプションを使用すると、切り詰められた文字列の各側に表示される文字数を定義できます。

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

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

is

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

use Illuminate\Support\Str;
 
$matches = Str::of('foobar')->is('foo*');
 
// true
 
$matches = Str::of('foobar')->is('baz*');
 
// false

isAscii

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

use Illuminate\Support\Str;
 
$result = Str::of('Taylor')->isAscii();
 
// true
 
$result = Str::of('ü')->isAscii();
 
// false

isEmpty

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

use Illuminate\Support\Str;
 
$result = Str::of(' ')->trim()->isEmpty();
 
// true
 
$result = Str::of('Laravel')->trim()->isEmpty();
 
// false

isNotEmpty

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

use Illuminate\Support\Str;
 
$result = Str::of(' ')->trim()->isNotEmpty();
 
// false
 
$result = Str::of('Laravel')->trim()->isNotEmpty();
 
// true

isJson

isJsonメソッドは、指定された文字列が有効なJSONかどうかを判断します。

use Illuminate\Support\Str;
 
$result = Str::of('[1,2,3]')->isJson();
 
// true
 
$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();
 
// true
 
$result = Str::of('{first: "John", last: "Doe"}')->isJson();
 
// false

isUlid

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

use Illuminate\Support\Str;
 
$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
 
// true
 
$result = Str::of('Taylor')->isUlid();
 
// false

isUrl

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

use Illuminate\Support\Str;
 
$result = Str::of('http://example.com')->isUrl();
 
// true
 
$result = Str::of('Taylor')->isUrl();
 
// false

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

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

isUuid

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

use Illuminate\Support\Str;
 
$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
 
// true
 
$result = Str::of('Taylor')->isUuid();
 
// false

kebab

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

use Illuminate\Support\Str;
 
$converted = Str::of('fooBar')->kebab();
 
// foo-bar

lcfirst

lcfirst メソッドは、指定された文字列の先頭の文字を小文字にした文字列を返します。

use Illuminate\Support\Str;
 
$string = Str::of('Foo Bar')->lcfirst();
 
// foo Bar

length

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

use Illuminate\Support\Str;
 
$length = Str::of('Laravel')->length();
 
// 7

limit

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 Flavored MarkdownをHTMLに変換します。

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

Markdownのセキュリティ

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

use Illuminate\Support\Str;
 
Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
 
// <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

mask

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

use Illuminate\Support\Str;
 
$string = Str::of('[email protected]')->mask('*', 3);
 
// tay***************

必要に応じて、mask メソッドの第三引数または第四引数に負の数を指定できます。これにより、文字列の末尾から指定された距離でマスクを開始するように指示します。

$string = Str::of('[email protected]')->mask('*', -15, 3);
 
// tay***@example.com
 
$string = Str::of('[email protected]')->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

関数の第2引数として整数を指定して、文字列の単数形または複数形を取得できます。

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 メソッドは、指定された文字列を繰り返します。

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フレンドリーな「slug」を生成します。

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 メソッドは、指定された値がまだ先頭でない場合、その値を文字列の先頭に1回追加します。

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.dokyumento.jp">Taylor <b>Otwell</b></a>')->stripTags();
 
// Taylor Otwell
 
$result = Str::of('<a href="https://laravel.dokyumento.jp">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()
 

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の場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

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

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

whenContains

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
->whenContains('tony', function (Stringable $string) {
return $string->title();
});
 
// 'Tony Stark'

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

与えられた文字列が配列内のいずれかの値を含むかどうかを判定するために、値の配列を渡すこともできます。

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
->whenContains(['tony', 'hulk'], function (Stringable $string) {
return $string->title();
});
 
// Tony Stark

whenContainsAll

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('tony stark')
->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
return $string->title();
});
 
// 'Tony Stark'

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

whenEmpty

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

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

whenNotEmpty

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

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

whenStartsWith

whenStartsWith メソッドは、文字列が指定された部分文字列で始まる場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

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 メソッドは、文字列が指定された部分文字列で終わる場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
return $string->title();
});
 
// 'Laravel'

whenNotExactly

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

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
return $string->title();
});
 
// 'Framework'

whenIs

whenIs メソッドは、文字列が指定されたパターンに一致する場合、指定されたクロージャを呼び出します。ワイルドカード値としてアスタリスクを使用できます。クロージャは、fluent stringインスタンスを受け取ります。

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の場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
return $string->title();
});
 
// 'Laravel'

whenIsUlid

whenIsUlid メソッドは、文字列が有効なULIDの場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

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

whenIsUuid

whenIsUuid メソッドは、文字列が有効なUUIDの場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
return $string->substr(0, 8);
});
 
// 'a0a2a2d2'

whenTest

whenTest メソッドは、文字列が指定された正規表現に一致する場合、指定されたクロージャを呼び出します。クロージャは、fluent stringインスタンスを受け取ります。

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
 
$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
return $string->title();
});
 
// 'Laravel Framework'

wordCount

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!