本文へ移動
Laravel Tips

文字列の操作

文字列を加工する Str クラスのメソッドとヘルパー関数、メソッドをつなげて書ける Str::of(Fluent Strings)を、全部の一覧と短い例つきで説明します。

Laravel には、文字列(文字の並び)を加工するための関数やメソッドが、たくさん用意されています。「前の部分だけ取り出す」「大文字にする」「URL に使える形にする」といった作業が、1行で書けます。Laravel 自身の中でも使われていますが、自分のアプリで使ってもかまいません。

3つの使い方#

文字列の道具には、使い方が3つあります。

  • Str:: のメソッド:Str::upper('laravel') のように、Str(Illuminate\Support\Str)にメソッド名を続けて呼びます。文字列を最初の引数に渡します
  • Fluent Strings(つなげて書く文字列):Str::of('laravel')->upper() のように、文字列を包んだオブジェクトにメソッドをつなげて呼びます。str('laravel') と書いても同じです。つなげて書くと、順番に読めるので読みやすくなります
  • ヘルパー関数:__() や e() のように、どこからでも呼べる関数(ヘルパー関数)です
php
use Illuminate\Support\Str;

// Str:: のメソッド
$upper = Str::upper('laravel');

// つなげて書く(Fluent Strings)
$title = Str::of('  laravel framework  ')
    ->trim()
    ->title();

// 'Laravel Framework'

Str:: のメソッドとヘルパー関数の一覧#

次の表に、すべてを目的ごとに並べます。例は、表のあとにまとめてあります。

ヘルパー関数#

名前 説明
__ 翻訳の文字列(またはキー)を、言語ファイルを使って訳す。無ければ、渡した値をそのまま返す
trans 翻訳のキーを、言語ファイルを使って訳す。無ければ、渡したキーをそのまま返す
trans_choice 数に合わせた言い回し(単数・複数など)で訳す。無ければ、渡したキーを返す
class_basename 名前空間(クラスの住所)を取りのぞいた、クラス名だけを返す
e HTML の特別な文字を変換する(PHP の htmlspecialchars。double_encode は、はじめから true)
preg_replace_array 正規表現(文字のパターンの書き方)に合う部分を、配列の値で順に置きかえる
str 文字列を、つなげて書ける Stringable にする(Str::of と同じ)。引数なしなら、Str のメソッドを呼ぶ窓口になる

前や後ろ・一部を取り出す#

名前 説明
Str::after 指定の値より後ろを返す。見つからなければ、文字列全体
Str::afterLast 指定の値が最後に出てくる場所より後ろを返す。見つからなければ、文字列全体
Str::before 指定の値より前を返す
Str::beforeLast 指定の値が最後に出てくる場所より前を返す
Str::between 2つの値にはさまれた部分を返す
Str::betweenFirst 2つの値にはさまれた、いちばん短い部分を返す
Str::charAt 指定の位置の文字を返す。範囲の外なら false
Str::substr 開始位置と長さを指定して、一部を返す
Str::take 先頭から指定の文字数だけ返す
Str::limit 指定の長さで切り、後ろに印(...)を付ける
Str::words 指定の単語数で切り、後ろに印を付ける
Str::excerpt 指定の語句のまわりだけを抜き出す
Str::position 指定の文字列が最初に出てくる位置を返す。無ければ false
Str::match 正規表現に合った最初の部分を返す
Str::matchAll 正規表現に合った部分すべてを、コレクションで返す
Str::ucsplit 大文字のところで区切って、配列にする

調べる#

名前 説明
Str::contains 指定の値(配列ならどれか)を含むか。大文字小文字は区別する
Str::containsAll 配列の値をすべて含むか
Str::doesntContain 指定の値(配列ならどれも)を含まないか
Str::startsWith 指定の値(配列ならどれか)で始まるか
Str::doesntStartWith 指定の値(配列ならどれも)で始まらないか
Str::endsWith 指定の値(配列ならどれか)で終わるか
Str::doesntEndWith 指定の値(配列ならどれも)で終わらないか
Str::is パターン(* が「なんでもよい」)に合うか
Str::isMatch 正規表現に合うか
Str::isAscii 7ビットの ASCII(英数字と記号)だけか
Str::isJson 正しい JSON か
Str::isUrl 正しい URL か(https などの、調べるプロトコルも指定できる)
Str::isUlid 正しい ULID(時刻順に並ぶ ID)か
Str::isUuid 正しい UUID(重なりにくい長い ID)か(バージョンも指定できる)
Str::length 文字数を返す
Str::wordCount 単語の数を返す
Str::substrCount 指定の値が何回出てくるかを返す

大文字・小文字・書き方を変える#

名前 説明
Str::camel camelCase(単語の頭だけ大文字でつなぐ)に変える
Str::kebab kebab-case(ハイフンでつなぐ)に変える
Str::snake snake_case(アンダースコアでつなぐ)に変える
Str::studly StudlyCase(すべての単語の頭を大文字でつなぐ)に変える
Str::title Title Case(各単語の頭を大文字)に変える
Str::headline 大文字・ハイフン・アンダースコアで区切られた言葉を、空白で区切って各単語の頭を大文字にする
Str::apa APA(アメリカ心理学会)のガイドラインに沿ったタイトルの書き方にする
Str::lower すべて小文字にする
Str::upper すべて大文字にする
Str::lcfirst 最初の1文字を小文字にする
Str::ucfirst 最初の1文字を大文字にする
Str::ucwords 各単語の最初の1文字を大文字にする
Str::initials 頭文字を返す(大文字にもできる)
Str::slug URL に使いやすい形(スラッグ)にする
Str::reverse 文字の並びを逆にする
Str::ascii ASCII の文字に置きかえようとする
Str::transliterate もっとも近い ASCII の表し方に変えようとする
Str::toBase64 Base64(文字を、英数字などの決まった文字だけで表す形式)にする
Str::fromBase64 Base64 を元に戻す
Str::markdown GitHub 風の Markdown を HTML にする(CommonMark を使う)
Str::inlineMarkdown Markdown を、段落などで包まない HTML にする

置きかえる・足す・取りのぞく・整える#

名前 説明
Str::replace 指定の文字列を置きかえる(大文字小文字を区別するかも選べる)
Str::replaceArray 指定の値を、配列の値で順に置きかえる
Str::replaceFirst 最初に出てくる1か所だけ置きかえる
Str::replaceLast 最後に出てくる1か所だけ置きかえる
Str::replaceMatches 正規表現に合う部分を、すべて置きかえる(関数も渡せる)
Str::replaceStart 指定の値が先頭にあるときだけ置きかえる
Str::replaceEnd 指定の値が末尾にあるときだけ置きかえる
Str::remove 指定の値(配列も可)を取りのぞく
Str::swap 複数の値を、まとめて置きかえる(PHP の strtr)
Str::substrReplace 指定の位置から、一部を置きかえる(長さ 0 なら差しこむ)
Str::chopStart 先頭に指定の値があるときだけ、取りのぞく
Str::chopEnd 末尾に指定の値があるときだけ、取りのぞく
Str::start 先頭に指定の値が無ければ、1つ足す
Str::finish 末尾に指定の値が無ければ、1つ足す
Str::wrap 前後を、指定の文字列ではさむ
Str::unwrap 前後にある、指定の文字列を取りのぞく
Str::trim 前後の空白(など)を取りのぞく。Unicode の空白も取りのぞく
Str::ltrim 左(前)の空白(など)を取りのぞく
Str::rtrim 右(後ろ)の空白(など)を取りのぞく
Str::squish 前後と、単語のあいだの余分な空白を取りのぞく
Str::deduplicate 続けて並んだ同じ文字を、1つにする(はじめは空白)
Str::padBoth 指定の長さになるまで、両側を埋める
Str::padLeft 指定の長さになるまで、左側を埋める
Str::padRight 指定の長さになるまで、右側を埋める
Str::repeat 文字列をくり返す
Str::mask 一部を、同じ文字でかくす(メールアドレスや電話番号など)
Str::wordWrap 指定の文字数で、折り返す

単数形・複数形#

名前 説明
Str::plural 英語の単数形を、複数形にする(数を渡すと、数に合う形にできる)
Str::pluralStudly StudlyCase の単語を複数形にする
Str::singular 複数形を単数形にする
Str::counted 数に合わせた形にして、数を前に付ける(1,000 orders)

ランダム・ID を作る#

名前 説明
Str::random ランダムな文字列を作る
Str::password 安全な、ランダムなパスワードを作る
Str::uuid UUID(バージョン4)を作る
Str::uuid7 UUID(バージョン7)を作る
Str::orderedUuid 「時刻が先」の UUID を作る。データベースの索引(検索用の目次)に、効率よく入る
Str::ulid ULID(短くて、時刻順に並ぶ ID)を作る

ヘルパー関数の例#

php
// __:翻訳(言語ファイルは「多言語対応」のページを参照)
echo __('Welcome to our application');

echo __('messages.welcome');
// キーが無ければ、'messages.welcome' がそのまま返る

echo trans('messages.welcome');

echo trans_choice('messages.notifications', $unreadCount);

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

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

// 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
$string = str('Taylor')->append(' Otwell');
// 'Taylor Otwell'

$snake = str()->snake('FooBar');
// 'foo_bar'

翻訳の使い方は、多言語対応のページにあります。

取り出す#

php
use Illuminate\Support\Str;

Str::after('This is my name', 'This is');
// ' my name'

Str::afterLast('App\Http\Controllers\Controller', '\\');
// 'Controller'

Str::before('This is my name', 'my name');
// 'This is '

Str::beforeLast('This is my name', 'is');
// 'This '

Str::between('This is my name', 'This', 'name');
// ' is my '

Str::betweenFirst('[a] bc [d]', '[', ']');
// 'a'

Str::charAt('This is my name.', 6);
// 's'

Str::substr('The Laravel Framework', 4, 7);
// Laravel

Str::take('Build something amazing!', 5);
// Build

Str::position('Hello, World!', 'Hello');
// 0

Str::position('Hello, World!', 'W');
// 7

Str::ucsplit('FooBar');
// [0 => 'Foo', 1 => 'Bar']

limit は、指定の長さで切ります。3番目の引数で、後ろに付ける印を変えられます。preserveWords: true なら、単語の途中で切らずに、手前の区切りで切ります。

php
Str::limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...

Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)

Str::limit('The quick brown fox', 12, preserveWords: true);
// The quick...

words は、単語の数で切ります。3番目の引数が、後ろに付ける印です。

php
Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// Perfectly balanced, as >>>

excerpt は、指定の語句のまわりだけを抜き出します。radius(語句の前後に残す文字数。はじめは 100)と、omission(前後に付ける印)を、オプションで指定できます。

php
$excerpt = Str::excerpt('This is my name', 'my', [
    'radius' => 3
]);
// '...is my na...'

$excerpt = Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]);
// '(...) my name'

match と matchAll は、正規表現(文字の並びのパターンを書く決まった書き方)で取り出します。

php
Str::match('/bar/', 'foo bar');
// 'bar'

Str::match('/foo (.*)/', 'foo bar');
// 'bar'

Str::matchAll('/bar/', 'bar foo bar');
// collect(['bar', 'bar'])

// グループ(かっこ)があれば、最初のグループの結果が集まる
Str::matchAll('/f(\w*)/', 'bar fun bar fly');
// collect(['un', 'ly'])

matchAll は、1つも合わなければ、空のコレクションを返します。

調べる#

php
Str::contains('This is my name', 'my');
// true

// 配列なら、どれか1つでも含めば true
Str::contains('This is my name', ['my', 'foo']);
// true

// 大文字小文字を区別しない
Str::contains('This is my name', 'MY', ignoreCase: true);
// true

Str::containsAll('This is my name', ['my', 'name']);
// true

Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true);
// true

Str::doesntContain('This is name', 'my');
// true

Str::doesntContain('This is name', ['my', 'framework']);
// true

Str::doesntContain('This is name', 'MY', ignoreCase: true);
// true

Str::startsWith('This is my name', 'This');
// true

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

Str::doesntStartWith('This is my name', 'That');
// true

Str::doesntStartWith('This is my name', ['What', 'That', 'There']);
// true

Str::endsWith('This is my name', 'name');
// true

Str::endsWith('This is my name', ['name', 'foo']);
// true

Str::endsWith('This is my name', ['this', 'foo']);
// false

Str::doesntEndWith('This is my name', 'dog');
// true

Str::doesntEndWith('This is my name', ['this', 'foo']);
// true

Str::doesntEndWith('This is my name', ['name', 'foo']);
// false
php
// is:* は「なんでもよい」
Str::is('foo*', 'foobar');
// true

Str::is('baz*', 'foobar');
// false

Str::is('*.jpg', 'photo.JPG', ignoreCase: true);
// true

Str::isMatch('/foo (.*)/', 'foo bar');
// true

Str::isMatch('/foo (.*)/', 'laravel');
// false

Str::isAscii('Taylor');
// true

Str::isAscii('ü');
// false

Str::isJson('[1,2,3]');
// true

Str::isJson('{"first": "John", "last": "Doe"}');
// true

Str::isJson('{first: "John", last: "Doe"}');
// false

Str::isUrl('http://example.com');
// true

Str::isUrl('laravel');
// false

// 正しいとみなすプロトコルを指定する
Str::isUrl('http://example.com', ['http', 'https']);

Str::isUlid('01gd6r360bp37zj17nxb55yv40');
// true

Str::isUlid('laravel');
// false

Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
// true

Str::isUuid('laravel');
// false

// バージョン(1、3、4、5、6、7、8)も確かめられる
Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4);
// true

Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1);
// false

Str::length('Laravel');
// 7

Str::wordCount('Hello, world!');
// 2

Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
// 2

isUrl は、はじめは幅広いプロトコル(http・https のような、URL の頭に付く通信の種類)を正しいとみなします。調べるプロトコルを限りたいときは、2番目の引数に配列で渡します。

書き方を変える#

php
Str::camel('foo_bar');
// fooBar

Str::kebab('fooBar');
// foo-bar

Str::snake('fooBar');
// foo_bar

// 2番目の引数で、つなぐ文字を変えられる
Str::snake('fooBar', '-');
// foo-bar

Str::studly('foo_bar');
// FooBar

Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct Case

Str::headline('steve_jobs');
// Steve Jobs

Str::headline('EmailNotificationSent');
// Email Notification Sent

Str::apa('Creating A Project');
// 'Creating a Project'

Str::lower('LARAVEL');
// laravel

Str::upper('laravel');
// LARAVEL

Str::lcfirst('Foo Bar');
// foo Bar

Str::ucfirst('foo bar');
// Foo bar

Str::ucwords('laravel framework');
// Laravel Framework

Str::initials('taylor otwell');
// to

Str::initials('taylor otwell', capitalize: true);
// TO

Str::slug('Laravel 5 Framework', '-');
// laravel-5-framework

Str::reverse('Hello World');
// dlroW olleH

Str::ascii('û');
// 'u'

Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
// 'test@laravel.com'

Str::toBase64('Laravel');
// TGFyYXZlbA==

Str::fromBase64('TGFyYXZlbA==');
// Laravel

Markdown を HTML にする#

php
$html = Str::markdown('# Laravel');
// <h1>Laravel</h1>

$html = Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]);
// <h1>Taylor Otwell</h1>

// 段落などで包まない、インラインの HTML にする
$html = Str::inlineMarkdown('**Laravel**');
// <strong>Laravel</strong>

注意

Markdown は、はじめのままでは、書かれた HTML もそのまま通します。利用者が入力した文字をそのまま渡すと、XSS(悪い人が仕込んだ命令が、ほかの人のブラウザで動いてしまう攻撃)の穴になります。html_input で HTML を取りのぞく(strip)か、文字にしてしまう(escape)ようにします。allow_unsafe_links で、危ないリンクを許すかも決められます。一部の HTML を通したいときは、できあがった HTML を「HTML Purifier」という道具に通します。

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

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

置きかえる・足す・取りのぞく・整える#

php
$string = 'Laravel 11.x';

Str::replace('11.x', '12.x', $string);
// Laravel 12.x

// はじめは大文字小文字を区別する。区別しないなら caseSensitive: false
Str::replace(
    'php',
    'Laravel',
    'PHP Framework for Web Artisans',
    caseSensitive: false
);
// Laravel Framework for Web Artisans

// ? を、配列の値で順に置きかえる
Str::replaceArray('?', ['8:30', '9:00'], 'The event will take place between ? and ?');
// The event will take place between 8:30 and 9:00

Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');
// a quick brown fox jumps over the lazy dog

Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');
// the quick brown fox jumps over a lazy dog

Str::replaceStart('Hello', 'Laravel', 'Hello World');
// Laravel World

Str::replaceStart('World', 'Laravel', 'Hello World');
// Hello World

Str::replaceEnd('World', 'Laravel', 'Hello World');
// Hello Laravel

Str::replaceEnd('Hello', 'Laravel', 'Hello World');
// Hello World

replaceMatches は、正規表現に合う部分を置きかえます。関数を渡すと、合った部分ごとに関数が呼ばれ、返した値で置きかわります。

php
Str::replaceMatches(
    pattern: '/[^A-Za-z0-9]++/',
    replace: '',
    subject: '(+1) 501-555-1000'
);
// '15015551000'

Str::replaceMatches('/\d/', function (array $matches) {
    return '['.$matches[0].']';
}, '123');
// '[1][2][3]'
php
$string = 'Peter Piper picked a peck of pickled peppers.';

Str::remove('e', $string);
// Ptr Pipr pickd a pck of pickld ppprs.

Str::swap([
    'Tacos' => 'Burritos',
    'great' => 'fantastic',
], 'Tacos are great!');
// Burritos are fantastic!

// 2番目の引数 2 から後ろを置きかえる
Str::substrReplace('1300', ':', 2);
// 13:

// 長さ 0 なら、置きかえずに差しこむ
Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'

Str::chopStart('http://laravel.com', ['https://', 'http://']);
// 'laravel.com'

Str::chopEnd('app/Models/Photograph.php', '.php');
// 'app/Models/Photograph'

Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);
// 'laravel.com'

Str::start('this/string', '/');
// /this/string

Str::start('/this/string', '/');
// /this/string

Str::finish('this/string', '/');
// this/string/

Str::finish('this/string/', '/');
// this/string/

Str::wrap('Laravel', '"');
// "Laravel"

Str::wrap('is', before: 'This ', after: ' Laravel!');
// This is Laravel!

Str::unwrap('-Laravel-', '-');
// Laravel

Str::unwrap('{framework: "Laravel"}', '{', '}');
// framework: "Laravel"

remove は、3番目の引数に false を渡すと、大文字小文字を区別せずに取りのぞきます。

php
Str::trim(' foo bar ');
// 'foo bar'

Str::ltrim('  foo bar  ');
// 'foo bar  '

Str::rtrim('  foo bar  ');
// '  foo bar'

Str::squish('    laravel    framework    ');
// laravel framework

Str::deduplicate('The   Laravel   Framework');
// The Laravel Framework

// 整える文字を変える
Str::deduplicate('The---Laravel---Framework', '-');
// The-Laravel-Framework

Str::padBoth('James', 10, '_');
// '__James___'

Str::padBoth('James', 10);
// '  James   '

Str::padLeft('James', 10, '-=');
// '-=-=-James'

Str::padLeft('James', 10);
// '     James'

Str::padRight('James', 10, '-');
// 'James-----'

Str::padRight('James', 10);
// 'James     '

Str::repeat('a', 5);
// aaaaa

trim・ltrim・rtrim は、PHP の trim などとちがい、Unicode(世界中の文字を1つの表にまとめた決まり)の空白文字も取りのぞきます。

mask は、一部を同じ文字でかくします。3番目の引数が、かくしはじめる位置です。マイナスなら、終わりからの位置になります。4番目の引数で、かくす長さも決められます。

php
Str::mask('taylor@example.com', '*', 3);
// tay***************

Str::mask('taylor@example.com', '*', -15, 3);
// tay***@example.com

wordWrap は、指定の文字数で折り返します。

php
$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.
*/

単数形・複数形#

英語の単語を、単数形と複数形に変えられます。Laravel の複数形の変換が対応している言語に、対応しています。

php
Str::plural('car');
// cars

Str::plural('child');
// children

// 数を渡すと、数に合う形になる
Str::plural('child', 2);
// children

Str::plural('child', 1);
// child

// prependCount で、数を前に付ける
Str::plural('car', 1000, prependCount: true);
// 1,000 cars

Str::pluralStudly('VerifiedHuman');
// VerifiedHumans

Str::pluralStudly('UserFeedback');
// UserFeedback

Str::pluralStudly('VerifiedHuman', 2);
// VerifiedHumans

Str::pluralStudly('VerifiedHuman', 1);
// VerifiedHuman

Str::singular('cars');
// car

Str::singular('children');
// child

Str::counted('order', 1);
// 1 order

Str::counted('order', 1000);
// 1,000 orders

複数形に対応する言語については、多言語対応のページを見てください。

ランダムな文字列と ID#

php
$random = Str::random(40);

$password = Str::password();
// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'  (はじめは32文字)

$password = Str::password(12);
// 'qwuar>#V|i]N'

return (string) Str::uuid();

return (string) Str::uuid7();

// uuid7 には、日時(DateTimeInterface)も渡せる
return (string) Str::uuid7(time: now());

return (string) Str::orderedUuid();

return (string) Str::ulid();
// 01gd6r360bp37zj17nxb55yv40

Str::random は、PHP の random_bytes を使います。Str::orderedUuid は、あとから作った UUID ほど後ろに並ぶので、データベースの索引(速く探すための目次)が付いた列に、むだなく保存できます。

ULID が作られた日時は、Carbon(日付と時刻を扱う道具)の createFromId で取り出せます。

php
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

$date = Carbon::createFromId((string) Str::ulid());

テストで固定した値にする#

テストのときは、ランダムな値を決まった値に差しかえると便利です。それぞれ「固定する」メソッドと「ふつうに戻す」メソッドがあります。

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

Str::createRandomStringsNormally();
php
// Str::ulid
use Symfony\Component\Uid\Ulid;

Str::createUlidsUsing(function () {
    return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});

Str::createUlidsNormally();
php
// Str::uuid
use Ramsey\Uuid\Uuid;

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

Str::createUuidsNormally();

Fluent Strings(つなげて書く文字列)#

Fluent Strings は、文字列をオブジェクトに包んで、メソッドをつなげて書けるようにしたものです。Str::of('...')(または str('...'))で作ります。「前の結果に、次の加工をする」を順に書けるので、読みやすくなります。

php
use Illuminate\Support\Str;

$string = Str::of('  laravel framework  ')
    ->trim()
    ->title()
    ->append('!');

// 'Laravel Framework!'

Fluent Strings のメソッド一覧#

Str:: にもあるメソッドは、文字列を最初の引数に渡さず、つなげて呼ぶ形になるだけで、同じ働きをします。ここでは、つなげて呼べるすべてのメソッドを挙げます。

名前 説明
after 指定の値より後ろを返す
afterLast 指定の値が最後に出てくる場所より後ろを返す
apa APA のガイドラインに沿ったタイトルの書き方にする
append 文字列の後ろに、値を足す
ascii ASCII の文字に置きかえようとする
basename パス(ファイルの場所を表す文字列)の、最後の部分(ファイル名)を返す。取りのぞく拡張子も指定できる
before 指定の値より前を返す
beforeLast 指定の値が最後に出てくる場所より前を返す
between 2つの値にはさまれた部分を返す
betweenFirst 2つの値にはさまれた、いちばん短い部分を返す
camel camelCase に変える
charAt 指定の位置の文字を返す。範囲の外なら false
classBasename 名前空間を取りのぞいた、クラス名だけを返す
chopStart 先頭に指定の値があるときだけ、取りのぞく
chopEnd 末尾に指定の値があるときだけ、取りのぞく
contains 指定の値(配列ならどれか)を含むか
containsAll 配列の値をすべて含むか
counted 数に合わせた形にして、数を前に付ける
decrypt 暗号化された文字列を、元に戻す
deduplicate 続けて並んだ同じ文字を、1つにする
dirname パスの、親のディレクトリ(フォルダ)の部分を返す
doesntContain 指定の値(配列ならどれも)を含まないか
doesntEndWith 指定の値(配列ならどれも)で終わらないか
doesntStartWith 指定の値(配列ならどれも)で始まらないか
encrypt 文字列を暗号化する
endsWith 指定の値(配列ならどれか)で終わるか
exactly 別の文字列と、完全に同じか
excerpt 指定の語句のまわりだけを抜き出す
explode 区切りの文字で分けて、コレクションにする
finish 末尾に指定の値が無ければ、1つ足す
fromBase64 Base64 を元に戻す
hash 指定のアルゴリズム(計算のやり方。sha256 など)で、ハッシュ(元に戻せない形)にする
headline 空白で区切って、各単語の頭を大文字にする
initials 頭文字にする
inlineMarkdown Markdown を、段落などで包まない HTML にする
is パターン(* が「なんでもよい」)に合うか
isAscii ASCII の文字だけか
isEmpty からっぽか
isNotEmpty からっぽでないか
isJson 正しい JSON か
isUlid 正しい ULID か
isUrl 正しい URL か
isUuid 正しい UUID か
kebab kebab-case に変える
lcfirst 最初の1文字を小文字にする
length 文字数を返す
limit 指定の長さで切る
lower すべて小文字にする
markdown Markdown を HTML にする
mask 一部を、同じ文字でかくす
match 正規表現に合った最初の部分を返す
matchAll 正規表現に合った部分すべてを、コレクションで返す
isMatch 正規表現に合うか
newLine 末尾に、改行を足す
padBoth 指定の長さになるまで、両側を埋める
padLeft 指定の長さになるまで、左側を埋める
padRight 指定の長さになるまで、右側を埋める
pipe 文字列を、呼び出せるもの(関数名や関数)に渡して変える
plural 複数形にする
position 指定の文字列が最初に出てくる位置を返す
prepend 文字列の前に、値を足す
remove 指定の値を取りのぞく
repeat 文字列をくり返す
replace 指定の文字列を置きかえる
replaceArray 指定の値を、配列の値で順に置きかえる
replaceFirst 最初に出てくる1か所だけ置きかえる
replaceLast 最後に出てくる1か所だけ置きかえる
replaceMatches 正規表現に合う部分を、すべて置きかえる
replaceStart 指定の値が先頭にあるときだけ置きかえる
replaceEnd 指定の値が末尾にあるときだけ置きかえる
scan sscanf の書式にしたがって、コレクションにする
singular 単数形にする
slug URL に使いやすい形(スラッグ)にする
snake snake_case に変える
split 正規表現で分けて、コレクションにする
squish 前後と、単語のあいだの余分な空白を取りのぞく
start 先頭に指定の値が無ければ、1つ足す
startsWith 指定の値(配列ならどれか)で始まるか
stripTags HTML や PHP のタグを取りのぞく
studly StudlyCase に変える
substr 開始位置と長さを指定して、一部を返す
substrReplace 指定の位置から、一部を置きかえる
swap 複数の値を、まとめて置きかえる
take 先頭から指定の文字数だけ返す
tap 途中で文字列をのぞき見る。文字列自体は変わらない
test 正規表現に合うか
title Title Case に変える
toBase64 Base64 にする
toHtmlString Blade で文字の変換をしない HtmlString にする
toUri Uri のオブジェクトにする
transliterate もっとも近い ASCII の表し方に変えようとする
trim 前後の空白(など)を取りのぞく
ltrim 左(前)の空白(など)を取りのぞく
rtrim 右(後ろ)の空白(など)を取りのぞく
ucfirst 最初の1文字を大文字にする
ucsplit 大文字のところで区切って、コレクションにする
ucwords 各単語の最初の1文字を大文字にする
unwrap 前後にある、指定の文字列を取りのぞく
upper すべて大文字にする
when 条件が true のとき、関数を実行する
whenContains 指定の値を含むとき、関数を実行する
whenContainsAll 指定の値をすべて含むとき、関数を実行する
whenDoesntEndWith 指定の値で終わらないとき、関数を実行する
whenDoesntStartWith 指定の値で始まらないとき、関数を実行する
whenEmpty からっぽのとき、関数を実行する
whenNotEmpty からっぽでないとき、関数を実行する
whenStartsWith 指定の値で始まるとき、関数を実行する
whenEndsWith 指定の値で終わるとき、関数を実行する
whenExactly 指定の文字列と完全に同じとき、関数を実行する
whenNotExactly 指定の文字列と完全には同じでないとき、関数を実行する
whenIs パターンに合うとき、関数を実行する
whenIsAscii ASCII の文字だけのとき、関数を実行する
whenIsUlid 正しい ULID のとき、関数を実行する
whenIsUuid 正しい UUID のとき、関数を実行する
whenTest 正規表現に合うとき、関数を実行する
wordCount 単語の数を返す
words 指定の単語数で切る
wrap 前後を、指定の文字列ではさむ

Str:: と同じ働きのメソッドの例#

php
Str::of('This is my name')->after('This is');
// ' my name'

Str::of('App\Http\Controllers\Controller')->afterLast('\\');
// 'Controller'

Str::of('a nice title uses the correct case')->apa();
// A Nice Title Uses the Correct Case

Str::of('ü')->ascii();
// 'u'

Str::of('This is my name')->before('my name');
// 'This is '

Str::of('This is my name')->beforeLast('is');
// 'This '

Str::of('This is my name')->between('This', 'name');
// ' is my '

Str::of('[a] bc [d]')->betweenFirst('[', ']');
// 'a'

Str::of('foo_bar')->camel();
// 'fooBar'

Str::of('This is my name.')->charAt(6);
// 's'

Str::of('Foo\Bar\Baz')->classBasename();
// 'Baz'

Str::of('https://laravel.com')->chopStart('https://');
// 'laravel.com'

Str::of('http://laravel.com')->chopStart(['https://', 'http://']);
// 'laravel.com'

Str::of('https://laravel.com')->chopEnd('.com');
// 'https://laravel'

Str::of('http://laravel.com')->chopEnd(['.com', '.io']);
// 'http://laravel'

Str::of('This is my name')->contains('my');
// true

Str::of('This is my name')->contains(['my', 'foo']);
// true

Str::of('This is my name')->contains('MY', ignoreCase: true);
// true

Str::of('This is my name')->containsAll(['my', 'name']);
// true

Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);
// true

Str::of('order')->counted(1);
// 1 order

Str::of('order')->counted(1000);
// 1,000 orders

Str::of('The   Laravel   Framework')->deduplicate();
// The Laravel Framework

// つなげて書く形では、整える文字は最初の引数
Str::of('The---Laravel---Framework')->deduplicate('-');
// The-Laravel-Framework

Str::of('This is name')->doesntContain('my');
// true

Str::of('This is name')->doesntContain(['my', 'framework']);
// true

Str::of('This is my name')->doesntContain('MY', ignoreCase: true);
// false

Str::of('This is my name')->doesntEndWith('dog');
// true

Str::of('This is my name')->doesntEndWith(['this', 'foo']);
// true

Str::of('This is my name')->doesntEndWith(['name', 'foo']);
// false

Str::of('This is my name')->doesntStartWith('That');
// true

Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);
// true

Str::of('This is my name')->endsWith('name');
// true

Str::of('This is my name')->endsWith(['name', 'foo']);
// true

Str::of('This is my name')->endsWith(['this', 'foo']);
// false

Str::of('this/string')->finish('/');
// this/string/

Str::of('this/string/')->finish('/');
// this/string/

Str::of('TGFyYXZlbA==')->fromBase64();
// Laravel

Str::of('taylor_otwell')->headline();
// Taylor Otwell

Str::of('EmailNotificationSent')->headline();
// Email Notification Sent
php
Str::of('foobar')->is('foo*');
// true

Str::of('foobar')->is('baz*');
// false

Str::of('Taylor')->isAscii();
// true

Str::of('ü')->isAscii();
// false

Str::of('[1,2,3]')->isJson();
// true

Str::of('{first: "John", last: "Doe"}')->isJson();
// false

Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
// true

Str::of('Taylor')->isUlid();
// false

Str::of('http://example.com')->isUrl();
// true

Str::of('Taylor')->isUrl();
// false

// 正しいとみなすプロトコルを指定する
Str::of('http://example.com')->isUrl(['http', 'https']);

Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
// true

Str::of('Taylor')->isUuid();
// false

// バージョンも確かめられる
Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4);
// true

Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1);
// false

Str::of('fooBar')->kebab();
// foo-bar

Str::of('Foo Bar')->lcfirst();
// foo Bar

Str::of('Laravel')->length();
// 7

Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox...

Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)

Str::of('The quick brown fox')->limit(12, preserveWords: true);
// The quick...

Str::of('LARAVEL')->lower();
// 'laravel'

Str::of('# Laravel')->markdown();
// <h1>Laravel</h1>

Str::of('# Taylor <b>Otwell</b>')->markdown([
    'html_input' => 'strip',
]);
// <h1>Taylor Otwell</h1>

Str::of('**Laravel**')->inlineMarkdown();
// <strong>Laravel</strong>

Str::of('taylor@example.com')->mask('*', 3);
// tay***************

Str::of('taylor@example.com')->mask('*', -15, 3);
// tay***@example.com

// 2番目と3番目の引数の、どちらもマイナスにできる
Str::of('taylor@example.com')->mask('*', 4, -4);
// tayl**********.com

Str::of('foo bar')->match('/bar/');
// 'bar'

Str::of('foo bar')->match('/foo (.*)/');
// 'bar'

Str::of('bar foo bar')->matchAll('/bar/');
// collect(['bar', 'bar'])

Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
// collect(['un', 'ly'])

Str::of('foo bar')->isMatch('/foo (.*)/');
// true

Str::of('laravel')->isMatch('/foo (.*)/');
// false

Str::of('James')->padBoth(10, '_');
// '__James___'

Str::of('James')->padLeft(10, '-=');
// '-=-=-James'

Str::of('James')->padRight(10, '-');
// 'James-----'

Str::of('car')->plural();
// cars

Str::of('child')->plural(2);
// children

Str::of('child')->plural(1);
// child

Str::of('car')->plural(1000, prependCount: true);
// 1,000 cars

Str::of('Hello, World!')->position('W');
// 7

Str::of('Arkansas is quite beautiful!')->remove('quite ');
// Arkansas is beautiful!

Str::of('a')->repeat(5);
// aaaaa

Str::of('Laravel 6.x')->replace('6.x', '7.x');
// Laravel 7.x

Str::of('macOS 13.x')->replace(
    'macOS', 'iOS', caseSensitive: false
);

$string = 'The event will take place between ? and ?';

Str::of($string)->replaceArray('?', ['8:30', '9:00']);
// The event will take place between 8:30 and 9:00

Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');
// a quick brown fox jumps over the lazy dog

Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');
// the quick brown fox jumps over a lazy dog

Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '');
// '15015551000'

Str::of('123')->replaceMatches('/\d/', function (array $matches) {
    return '['.$matches[0].']';
});
// '[1][2][3]'

Str::of('Hello World')->replaceStart('Hello', 'Laravel');
// Laravel World

Str::of('Hello World')->replaceEnd('World', 'Laravel');
// Hello Laravel

Str::of('cars')->singular();
// car

Str::of('Laravel Framework')->slug('-');
// laravel-framework

Str::of('fooBar')->snake();
// foo_bar

Str::of('    laravel    framework    ')->squish();
// laravel framework

Str::of('this/string')->start('/');
// /this/string

Str::of('This is my name')->startsWith('This');
// true

Str::of('This is my name')->startsWith(['This', 'That']);
// true

Str::of('foo_bar')->studly();
// FooBar

Str::of('Laravel Framework')->substr(8);
// Framework

Str::of('Laravel Framework')->substr(8, 5);
// Frame

Str::of('1300')->substrReplace(':', 2);
// 13:

Str::of('The Framework')->substrReplace(' Laravel', 3, 0);
// The Laravel Framework

Str::of('Tacos are great!')
    ->swap([
        'Tacos' => 'Burritos',
        'great' => 'fantastic',
    ]);
// Burritos are fantastic!

Str::of('Build something amazing!')->take(5);
// Build

Str::of('a nice title uses the correct case')->title();
// A Nice Title Uses The Correct Case

Str::of('Laravel')->toBase64();
// TGFyYXZlbA==

Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate();
// 'test@laravel.com'

Str::of('  Laravel  ')->trim();
// 'Laravel'

Str::of('/Laravel/')->trim('/');
// 'Laravel'

Str::of('  Laravel  ')->ltrim();
// 'Laravel  '

Str::of('/Laravel/')->ltrim('/');
// 'Laravel/'

Str::of('  Laravel  ')->rtrim();
// '  Laravel'

Str::of('/Laravel/')->rtrim('/');
// '/Laravel'

Str::of('foo bar')->ucfirst();
// Foo bar

Str::of('laravel framework')->ucwords();
// Laravel Framework

Str::of('-Laravel-')->unwrap('-');
// Laravel

Str::of('{framework: "Laravel"}')->unwrap('{', '}');
// framework: "Laravel"

Str::of('laravel')->upper();
// LARAVEL

Str::of('Hello, world!')->wordCount();
// 2

Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Perfectly balanced, as >>>

Str::of('Laravel')->wrap('"');
// "Laravel"

Str::of('is')->wrap(before: 'This ', after: ' Laravel!');
// This is Laravel!

excerpt は、radius と omission のオプションを渡せます。

php
$excerpt = Str::of('This is my name')->excerpt('my', [
    'radius' => 3
]);
// '...is my na...'

$excerpt = Str::of('This is my name')->excerpt('name', [
    'radius' => 3,
    'omission' => '(...) '
]);
// '(...) my name'

Markdown の変換には、Str:: の場合と同じ注意があります。利用者の入力を渡すときは、html_input と allow_unsafe_links を指定します。

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

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

remove は、2番目の引数に false を渡すと、大文字小文字を区別せずに取りのぞきます。

つなげて書く形だけのメソッド#

php
// append:後ろに足す
Str::of('Taylor')->append(' Otwell');
// 'Taylor Otwell'

// prepend:前に足す
Str::of('Framework')->prepend('Laravel ');
// Laravel Framework

// newLine:改行を足す
Str::of('Laravel')->newLine()->append('Framework');
// 'Laravel
//  Framework'

// basename:パスの最後の部分
Str::of('/foo/bar/baz')->basename();
// 'baz'

// 取りのぞく拡張子も指定できる
Str::of('/foo/bar/baz.jpg')->basename('.jpg');
// 'baz'

// dirname:親のディレクトリ
Str::of('/foo/bar/baz')->dirname();
// '/foo/bar'

// さかのぼる階層の数も指定できる
Str::of('/foo/bar/baz')->dirname(2);
// '/foo'

// exactly:完全に同じか
Str::of('Laravel')->exactly('Laravel');
// true

// explode:区切りの文字で分けて、コレクションにする
Str::of('foo bar baz')->explode(' ');
// collect(['foo', 'bar', 'baz'])

// split:正規表現で分けて、コレクションにする
Str::of('one, two, three')->split('/[\s,]+/');
// collect(["one", "two", "three"])

// scan:sscanf の書式で読みとって、コレクションにする
Str::of('filename.jpg')->scan('%[^.].%s');
// collect(['filename', 'jpg'])

// ucsplit:大文字のところで区切って、コレクションにする
Str::of('Foo Bar')->ucsplit();
// collect(['Foo ', 'Bar'])

// initials:頭文字
Str::of('Taylor Otwell')->initials()->upper();
// TO

// hash:指定のアルゴリズムでハッシュにする
Str::of('secret')->hash(algorithm: 'sha256');
// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'

// isEmpty と isNotEmpty
Str::of('  ')->trim()->isEmpty();
// true

Str::of('Laravel')->trim()->isEmpty();
// false

Str::of('  ')->trim()->isNotEmpty();
// false

Str::of('Laravel')->trim()->isNotEmpty();
// true

// test:正規表現に合うか(isMatch と同じ)
Str::of('Laravel Framework')->test('/Laravel/');
// true

// stripTags:HTML と PHP のタグを取りのぞく
Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags();
// Taylor Otwell

// 残したいタグも指定できる
Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags('<b>');
// Taylor <b>Otwell</b>

encrypt と decrypt は、暗号化のしくみで、文字列を暗号化したり元に戻したりします。

php
$encrypted = Str::of('secret')->encrypt();

$decrypted = $encrypted->decrypt();
// 'secret'

toHtmlString は、Blade で表示するときに、HTML の特別な文字を変換しない文字列(HtmlString)にします。toUri は、Illuminate\Support\Uri のオブジェクトにします。

php
$htmlString = Str::of('Nuno Maduro')->toHtmlString();

$uri = Str::of('https://example.com')->toUri();

pipe は、文字列を関数名や関数に渡して、結果に置きかえます。tap は、途中の文字列を見るためのもので、関数が何を返しても、元の文字列がつづきます。

php
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'

$string = Str::of('Laravel')
    ->append(' Framework')
    ->tap(function (Stringable $string) {
        dump('String after append: '.$string);
    })
    ->upper();
// LARAVEL FRAMEWORK

条件で動かす(when 系のメソッド)#

when から始まるメソッドは、条件に合うときだけ関数を実行します。関数には、つなげて書ける文字列(Stringable)が渡されます。

when は、最初の引数が true のときに実行します。3番目の引数に別の関数を渡すと、false のときに実行されます。

php
use Illuminate\Support\Stringable;

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

そのほかの when 系は、それぞれ条件が決まっています。whenContains と whenContainsAll も、3番目の引数に別の関数を渡すと、条件に合わなかったときに実行されます。

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

// 配列なら、どれか1つでも含めば実行される
$string = Str::of('tony stark')
    ->whenContains(['tony', 'hulk'], function (Stringable $string) {
        return $string->title();
    });
// Tony Stark

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

$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) {
    return $string->title();
});
// 'Disney World'

$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
    return $string->title();
});
// 'Disney World'

$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
    return $string->title();
});
// 'Disney World'

$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
    return $string->title();
});
// 'Disney World'

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

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

$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {
    return $string->append('/baz');
});
// 'foo/bar/baz'

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

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

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

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

whenEmpty と whenNotEmpty は、関数が値を返したときは、その値がメソッドの結果になります。何も返さなかったときは、つなげて書ける文字列がそのまま返ります。

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

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

関連するページ#

公式ドキュメント(英語)

2026年10月5日時点の内容をもとに、日本語でまとめています。

ページの一覧