laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
# 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 includes a variety of string manipulation helpers through the `Str` extension trait, available directly on every `&str` and `String` for common tasks like generating URL slugs, formatting field labels, and truncating previews. Because the [prelude](prelude.md) imports `Str`, these methods are ready to use throughout your application:

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

In a file that does not import the prelude, bring the trait into scope with `use laravel::str::Str`.

All lengths, positions, and widths operate on Unicode characters rather than raw bytes, so `"这是一段中文".take(2)` returns `"这是"`. Methods that slice part of the input (such as `after` and `take`) return a borrowed `&str`, while methods that transform text return a new `String`.

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

The tables below list the methods provided by the `Str` trait, grouped by category.

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

Use these methods to convert identifiers and titles between naming conventions:

| Method | Result |
| --- | --- |
| `"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` |

A slug keeps accented letters, so `"Café".slug()` is `café`. To drop the accents too, call `ascii` first.

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

| Method | Result |
| --- | --- |
| `"photo".plural()` | `photos` |
| `"category".plural()` | `categories` |
| `"child".plural()` | `children` |
| `"BlogPost".plural()` | `BlogPosts` |
| `"blog_posts".singular()` | `blog_post` |
| `"people".singular()` | `person` |

`plural` and `singular` use English rules. In a name such as `BlogPost`, they change the last word and keep its case.

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

These methods cut a string at a search string, a prefix, a suffix, or a number of characters:

| Method | Result |
| --- | --- |
| `"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` |

When the string doesn't contain the search, these methods return the whole string.

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

| Method | Result |
| --- | --- |
| `"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` and `finish` add the prefix or suffix only when the string doesn't already have it, so `"/this/string".start("/")` is still `/this/string`. `replace_start` and `replace_end` change the text only when the string starts or ends with the search.

To replace every match, use the standard library's `replace`. To replace only the first, use `replacen(search, replace, 1)`.

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

When you show a long post or comment in a list, you'll want a preview that fits. `limit` cuts to a number of characters and `words` cuts to a number of words:

| Method | Result |
| --- | --- |
| `"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` and `words` add the ending only when they cut the string, and the ending doesn't count toward the limit. `excerpt` returns the phrase with up to `radius` characters on each side, or `None` when the phrase isn't there.

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

| Method | Result |
| --- | --- |
| `"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` takes a range of character positions, counted from the start. To show only the last four digits of a 16-digit card number, mask `..12`. When the string is already as wide as the width you pass, the padding methods return it unchanged.

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

`resembles` checks a string against a pattern in which `*` matches any characters, including none. The match is case-sensitive and must cover the whole string, which makes it useful for checking a path against a list of patterns:

```rust
"posts/1/edit".resembles("posts/*");   // true
"posts/1/edit".resembles("*/edit");    // true
"posts".resembles("posts/*");          // false
```

For a plain substring, prefix, or suffix, use the standard library's `contains`, `starts_with`, and `ends_with`. For more complex patterns, use the [`regex`](https://docs.rs/regex) crate.

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

When generating invitation links, API tokens, or unique identifiers, use the functions in `laravel::str`, which draw from the operating system's cryptographically secure random number generator:

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

Because `uuid7` and `ulid` embed a creation timestamp at the start, they sort chronologically and append cleanly to database B-tree indexes, making them a better choice for primary keys than random `uuid` values.

`random` and `password` return a `String`, while `uuid`, `uuid7`, and `ulid` return typed `Uuid` and `Ulid` values (call `.to_string()` when you need a string representation). Both `Uuid` and `Ulid` work directly in models, queries, and route parameters. Models with a `Uuid` or `Ulid` [primary key](models.md#primary-keys) generate IDs automatically on creation, so call `uuid7` or `ulid` directly only when generating identifiers outside a model key.