# Strings

- [Introduction](#introduction)
- [Available methods](#available-methods)
    - [Case](#case)
    - [Plurals](#plurals)
    - [Substrings](#substrings)
    - [Replacing](#replacing)
    - [Shortening and wrapping](#shortening-and-wrapping)
    - [Padding, masking, and cleaning](#padding-masking-and-cleaning)
    - [Matching](#matching)
- [Random strings and identifiers](#random-strings-and-identifiers)

<a name="introduction"></a>

## Introduction


Laravel은 `Str` 확장 트레이트로 다양한 문자열 처리 헬퍼를 제공합니다. 모든 `&str`과 `String`에서 바로 사용할 수 있어 URL 슬러그 생성, 필드 레이블 형식 지정, 미리보기 자르기 같은 작업에 유용합니다. [prelude](/rust/docs/prelude)가 `Str`을 가져오므로 애플리케이션 어디서나 이 메서드를 사용할 수 있습니다.

```rust
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`로 트레이트를 스코프에 가져옵니다.


모든 길이, 위치, 너비는 원시 바이트가 아닌 유니코드 문자 기준으로 동작하므로 `"这是一段中文".take(2)`는 `"这是"`를 반환합니다. 입력 일부를 잘라내는 메서드(`after`, `take` 등)는 빌린 `&str`을 반환하고, 텍스트를 변환하는 메서드는 새로운 `String`을 반환합니다.

<a name="available-methods"></a>

## Available methods


아래 표는 `Str` 트레이트가 제공하는 메서드를 범주별로 보여 줍니다.

<a name="case"></a>

### 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`를 먼저 호출합니다.

<a name="plurals"></a>

### Plurals

| 메서드 | 결과 |
| --- | --- |
| `"photo".plural()` | `photos` |
| `"category".plural()` | `categories` |
| `"child".plural()` | `children` |
| `"BlogPost".plural()` | `BlogPosts` |
| `"blog_posts".singular()` | `blog_post` |
| `"people".singular()` | `person` |


`plural`과 `singular`는 영어 규칙을 사용합니다. `BlogPost` 같은 이름에서는 마지막 단어를 바꾸며 대소문자를 유지합니다.

<a name="substrings"></a>

### 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` |


문자열에 검색 대상이 없으면 이 메서드들은 문자열 전체를 반환합니다.

<a name="replacing"></a>

### 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)`을 사용합니다.

<a name="shortening-and-wrapping"></a>

### 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`을 반환합니다.

<a name="padding-masking-and-cleaning"></a>

### Padding, masking, and cleaning

| 메서드 | 결과 |
| --- | --- |
| `"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자리 카드 번호의 마지막 네 자리만 보이게 하려면 `..12`를 가립니다. 문자열 너비가 이미 전달한 너비에 도달했다면 패딩 메서드는 원래 문자열을 그대로 반환합니다.

<a name="matching"></a>

### Matching


`resembles`는 `*`가 0개 이상의 임의 문자를 나타내는 패턴과 문자열을 비교합니다. 대소문자를 구분하고 문자열 전체가 일치해야 하므로 경로를 패턴 목록과 대조할 때 유용합니다.

```rust
"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) 크레이트를 사용합니다.

<a name="random-strings-and-identifiers"></a>

## Random strings and identifiers


초대 링크, API 토큰, 고유 식별자를 생성할 때는 운영체제의 암호학적으로 안전한 난수 생성기를 사용하는 `laravel::str`의 함수들을 사용합니다.

```rust
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](/rust/docs/models#primary-keys)를 가진 모델은 생성 시 ID를 자동으로 생성하므로, 모델 키 외부에서 식별자를 생성할 때만 `uuid7`이나 `ulid`를 직접 호출하세요.