LoginSignup
0
0

More than 1 year has passed since last update.

個人的な初知りな便利文字列操作系へルパ

Last updated at Posted at 2022-12-20

概要

Laravelが用意してくれている便利な文字列操作系ヘルパの中で、使えそうなのをピックアップ

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番目の引数を渡し、切り捨てる文字列の末尾へ追加する文字列を変更できます。

use Illuminate\Support\Str;

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

// The quick brown fox (...)

Str::mask()

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

use Illuminate\Support\Str;

$string = Str::mask('taylor@example.com', '*', 3);

// tay***************

必要であれば、maskメソッドの第3引数に負の数を指定し、文字列の最後から指定する文字数分戻った箇所からマスキングを開始するように指示できます。

$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::uuid()

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

use Illuminate\Support\Str;

return (string) Str::uuid();

Str::replace()

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

use Illuminate\Support\Str;

$string = 'Laravel 8.x';

$replaced = Str::replace('8.x', '9.x', $string);

// Laravel 9.x

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0