Strings
Introduction
Laravelは Str 拡張トレイトでさまざまな文字列操作ヘルパーを提供します。すべての &str と String で直接利用でき、URLスラッグの生成、フィールドラベルの整形、プレビューの切り詰めなどに使えます。prelude が Str をインポートするため、アプリケーション全体でこれらのメソッドを利用できます。
use laravel::prelude::*;
let slug = "My First Post".slug(); // my-first-post
let label = "first_name".headline(); // First Name
let table = "BlogPost".snake().plural(); // blog_posts
let preview = "Thanks for the detailed write-up on queues".limit(20); // Thanks for the detai...
preludeをインポートしないファイルでは、use laravel::str::Str でトレイトをスコープに取り込みます。
すべての長さ、位置、幅は生のバイトではなくUnicode文字単位で扱うため、"这是一段中文".take(2) は "这是" を返します。入力の一部を切り出すメソッド(after や take など)は借用した &str を返し、テキストを変換するメソッドは新しい String を返します。
Available methods
以下の表は、Str トレイトが提供するメソッドを分類別に示しています。
Case
次のメソッドは、識別子やタイトルを異なる命名規則に変換します。
| メソッド | 結果 |
|---|---|
"LaravelRustFramework".snake() | laravel_rust_framework |
"LaravelRustFramework".kebab() | laravel-rust-framework |
"laravel_rust_framework".studly() | LaravelRustFramework |
"laravel_rust_framework".camel() | laravelRustFramework |
"a nice title uses the correct case".title() | A Nice Title Uses The Correct Case |
"EmailNotificationSent".headline() | Email Notification Sent |
"taylor otwell".upper_first() | Taylor otwell |
"Taylor".lower_first() | taylor |
"laravelRust".split_upper() | ["laravel", "Rust"] |
"Hello World!".slug() | hello-world |
"Hello World!".slug_with("_") | hello_world |
"Ünïcödé".ascii() | Unicode |
スラッグはアクセント付き文字を保持するため、"Café".slug() は café になります。アクセントも取り除くには、先に ascii を呼び出します。
Plurals
| メソッド | 結果 |
|---|---|
"photo".plural() | photos |
"category".plural() | categories |
"child".plural() | children |
"BlogPost".plural() | BlogPosts |
"blog_posts".singular() | blog_post |
"people".singular() | person |
plural と singular は英語の規則を使います。BlogPost のような名前では、最後の単語を変更し、大文字小文字を保持します。
Substrings
次のメソッドは、検索文字列、接頭辞、接尾辞、または文字数を基準に文字列を切り出します。
| メソッド | 結果 |
|---|---|
"app/Http/Kernel".after("/") | Http/Kernel |
"app/Http/Kernel".after_last("/") | Kernel |
"app/Http/Kernel".before("/") | app |
"app/Http/Kernel".before_last("/") | app/Http |
"[a] and [b]".between("[", "]") | a] and [b |
"[a] and [b]".between_first("[", "]") | a |
"https://laravel.com".chop_start("https://") | laravel.com |
"Photograph.rs".chop_end(".rs") | Photograph |
"Build something amazing!".take(5) | Build |
文字列に検索対象が含まれていない場合、これらのメソッドは文字列全体を返します。
Replacing
| メソッド | 結果 |
|---|---|
"this/string".start("/") | /this/string |
"this/string".finish("/") | this/string/ |
"the fox the dog".replace_last("the", "a") | the fox a dog |
"Hello World".replace_start("Hello", "Laravel") | Laravel World |
"Hello World".replace_end("World", "Laravel") | Hello Laravel |
"Tacos are great!".swap(&[("Tacos", "Burritos"), ("great", "fantastic")]) | Burritos are fantastic! |
start と finish は文字列に接頭辞や接尾辞がまだない場合だけ追加するため、"/this/string".start("/") は /this/string のままです。replace_start と replace_end は、文字列の先頭または末尾が検索対象と一致する場合だけ変更します。
一致する箇所をすべて置換するには、標準ライブラリの replace を使います。最初の一致だけを置換するには、replacen(search, replace, 1) を使います。
Shortening and wrapping
長い投稿やコメントを一覧に表示するときは、表示範囲に収まるプレビューが必要です。limit は文字数、words は単語数で切り詰めます。
| メソッド | 結果 |
|---|---|
"The quick brown fox".limit(9) | The quick... |
"The quick brown fox".limit_with(9, " →") | The quick → |
"Perfectly balanced, as all things should be.".words(3) | Perfectly balanced, as... |
"Perfectly balanced, as all things should be.".words_with(3, " >>>") | Perfectly balanced, as >>> |
"This is my name".excerpt("my", 3) | Some("...is my na...") |
"The quick brown fox".word_wrap(10) | The quick\nbrown fox |
"Hello world".word_count() | 2 |
limit と words は文字列を切り詰めたときだけ末尾文字列を追加し、その末尾文字列は制限に含めません。excerpt はフレーズとその両側最大 radius 文字を返し、フレーズがない場合は None を返します。
Padding, masking, and cleaning
| メソッド | 結果 |
|---|---|
"42".pad_start(5, '0') | 00042 |
"James".pad_end(10, '-') | James----- |
"James".pad_both(10, '_') | __James___ |
"[email protected]".mask('*', 3..) | tay*************** |
"4242424242424242".mask('*', ..12) | ************4242 |
" laravel framework ".squish() | laravel framework |
"/docs//strings///methods".deduplicate('/') | /docs/strings/methods |
"(555) 123-4567".digits() | 5551234567 |
mask は先頭から数えた文字位置の範囲を受け取ります。16桁のカード番号の下4桁だけを表示するには、..12 をマスクします。文字列が指定した幅をすでに満たしている場合、パディング用メソッドは変更せずに返します。
Matching
resembles は、* が0文字以上の任意の文字に一致するパターンと文字列を照合します。大文字小文字を区別し、文字列全体が一致する必要があるため、パスをパターンの一覧と照合するのに役立ちます。
"posts/1/edit".resembles("posts/*"); // true
"posts/1/edit".resembles("*/edit"); // true
"posts".resembles("posts/*"); // false
単純な部分文字列、接頭辞、接尾辞には、標準ライブラリの contains、starts_with、ends_with を使います。より複雑なパターンには regex クレートを使います。
Random strings and identifiers
招待リンク、APIトークン、一意の識別子を生成するときは、OSの暗号学的に安全な乱数生成器を使う laravel::str の関数を利用します。
use laravel::str::{self, Ulid, Uuid};
let token: String = str::random(40); // 40 letters and digits
let password: String = str::password(16); // letters, digits, and symbols
let id: Uuid = str::uuid(); // a version 4 UUID
let ordered: Uuid = str::uuid7(); // a version 7 UUID, which sorts by time
let ulid: Ulid = str::ulid(); // a ULID, such as 01K7XRWX0E4CMFRGZ8F5T0XFJN
uuid7 と ulid は先頭に作成時刻を埋め込むため、時系列に並び、データベースのB-treeインデックスにも順に追加できます。そのため、ランダムな uuid 値より主キーに適しています。
random と password は String を返し、uuid、uuid7、ulid は型付きの Uuid と Ulid の値を返します(文字列表現が必要な場合は .to_string() を呼び出します)。Uuid と Ulid はどちらもモデル、クエリ、ルートパラメータで直接利用できます。Uuid または Ulid の primary key を持つモデルは作成時にIDを自動生成するため、モデルのキー以外で識別子を生成するときだけ uuid7 や ulid を直接呼び出してください。