> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 文字列

> Laravel for Rust の文字列操作ヘルパー（Str トレイトの大文字小文字、複数形、部分文字列、置換、切り詰め、マスク、マッチ、ランダム文字列と ID）の使い方を解説します。

## はじめに

Laravel は、さまざまな文字列操作ヘルパーを、`Str` 拡張トレイトを通して含み、それらは、すべての `&str` と `String` で、直接利用可能であり、一般的なタスクについての、URL スラッグを生成する、フィールドラベルをフォーマットする、プレビューを切り捨てるような。[プリリュード](https://kawax.biz/jp/rust/prelude.md)が、`Str` をインポートするため、これらのメソッドは、アプリケーション全体で、使う準備ができています。

```rust theme={null}
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...
```

プリリュードをインポートしないファイルでは、そのトレイトを、`use laravel::str::Str` でスコープへ持ってきます。

すべての長さ、位置、幅は、生のバイトではなく、Unicode 文字で動作するため、`"这是一段中文".take(2)` は、`"这是"` を返します。入力の一部をスライスするメソッド（`after` と `take` のような）は、借用された `&str` を返し、テキストを変換するメソッドは、新しい `String` を返します。

## 利用可能なメソッド

以下のテーブルは、`Str` トレイトが提供するメソッドをリストし、カテゴリでグループ化されます。

### 大文字小文字

これらのメソッドを使い、識別子とタイトルを、命名規則の間で変換します。

| メソッド | 結果 |
| - | - |
| `"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` を呼びます。

### 複数形

| メソッド | 結果 |
| - | - |
| `"photo".plural()` | `photos` |
| `"category".plural()` | `categories` |
| `"child".plural()` | `children` |
| `"BlogPost".plural()` | `BlogPosts` |
| `"blog_posts".singular()` | `blog_post` |
| `"people".singular()` | `person` |

`plural` と `singular` は、英語のルールを使います。`BlogPost` のような名前では、それらは、最後の単語を変更し、そのケースを保持します。

### 部分文字列

これらのメソッドは、文字列を、検索文字列、接頭辞、接尾辞、文字数で切ります。

| メソッド | 結果 |
| - | - |
| `"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` |

その文字列が、その検索を含まない場合は、これらのメソッドは、全体の文字列を返します。

### 置換

| メソッド | 結果 |
| - | - |
| `"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)` を使います。

### 短縮と折り返し

長い投稿や、コメントを、リストに表示する場合は、収まるプレビューを望むでしょう。`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` を返します。

### パディング、マスク、クリーンアップ

| メソッド | 結果 |
| - | - |
| `"42".pad_start(5, '0')` | `00042` |
| `"James".pad_end(10, '-')` | `James-----` |
| `"James".pad_both(10, '_')` | `__James___` |
| `"taylor@example.com".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` をマスクします。その文字列が、すでに、渡す幅と同じ広さである場合は、そのパディングメソッドは、それを、変更されずに返します。

### マッチ

`resembles` は、文字列を、パターンに対してチェックし、それでは、`*` は、任意の文字に一致し、なしを含みます。そのマッチは、大文字小文字を区別し、全体の文字列をカバーしなければならず、それは、パスを、パターンのリストに対してチェックするのに有用にします。

```rust theme={null}
"posts/1/edit".resembles("posts/*");   // true
"posts/1/edit".resembles("*/edit");    // true
"posts".resembles("posts/*");          // false
```

平文の部分文字列、接頭辞、接尾辞については、標準ライブラリの `contains`、`starts_with`、`ends_with` を使います。より複雑なパターンについては、[`regex`](https://docs.rs/regex) クレートを使います。

## ランダム文字列と識別子

招待リンク、API トークン、一意の識別子を生成する場合は、`laravel::str` の関数を使い、それらは、オペレーティングシステムの、暗号学的に安全な乱数生成器から引きます。

```rust theme={null}
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` の[主キー](https://kawax.biz/jp/rust/models.md#主キー)を持つモデルは、作成時に、ID を自動的に生成するため、`uuid7` や `ulid` を、直接呼ぶのは、モデルのキーの外で、識別子を生成する場合だけです。


## Related topics

- [文字列と数値](https://kawax.biz/jp/go/strings.md)
- [文字列操作（Str クラス）](https://kawax.biz/jp/strings.md)
- [パッケージの文字列バリデーションルール登録](https://kawax.biz/jp/advanced/package-validation-extensions.md)
- [コレクションの高階メッセージ](https://kawax.biz/jp/advanced/higher-order-messages.md)
- [Eloquentのカスタムキャスト](https://kawax.biz/jp/advanced/eloquent-casts.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.