跳至正文

字符串 ​

简介 ​

Laravel 通过 Str 扩展 trait 提供多种字符串处理方法,可以直接在任意 &str 和 String 上调用,例如生成 URL 的 slug、格式化字段标签和截取预览文本。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 将该 trait 引入作用域。

长度、位置和宽度都按 Unicode 字符计算,因此 "这是一段中文".take(2) 返回 "这是"。截取部分输入的方法(例如 after 和 take)返回借用的 &str,转换文本的方法则返回新的 String。

可用方法 ​

以下按用途列出 Str trait 提供的方法。

大小写与命名格式 ​

可以使用这些方法在不同命名风格之间转换标识符和标题:

方法结果
"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

生成 slug 时会保留带有重音符号的字母,例如 "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 位卡号的后四位时,可以遮盖 ..12。字符串已经达到指定宽度时,填充方法会返回原字符串。

模式匹配 ​

resembles 检查字符串是否匹配指定模式,其中 * 可以匹配任意数量的字符,也可以匹配空字符串。匹配区分大小写,并且必须覆盖整个字符串,因此很适合检查某个路径是否符合一组模式:

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

要检查普通子串、前缀或后缀,请使用标准库的 contains、starts_with 和 ends_with。处理更复杂的模式时,可以使用 regex crate。

随机字符串与标识符 ​

要生成邀请链接、API 令牌或唯一标识符,可以使用 laravel::str 中的函数。它们使用操作系统提供的密码学安全随机数生成器:

rust
use laravel::str::{self, Ulid, Uuid};

let token: String = str::random(40);         // 由字母和数字组成的 40 个字符
let password: String = str::password(16);    // 包含字母、数字和符号
let id: Uuid = str::uuid();                  // 版本 4 的 UUID
let ordered: Uuid = str::uuid7();            // 版本 7 的 UUID,可按时间排序
let ulid: Ulid = str::ulid();                // 一个 ULID,例如 01K7XRWX0E4CMFRGZ8F5T0XFJN

uuid7 和 ulid 的开头包含创建时间戳,因此可以按时间排序。在数据库 B 树索引中,新值会顺序追加,比随机的 uuid 更适合作为主键。

random 和 password 返回 String,uuid、uuid7 和 ulid 则返回带类型的 Uuid 或 Ulid 值。需要字符串时,可调用 .to_string()。Uuid 和 Ulid 都可直接用于模型、查询和路由参数。使用这两种类型之一作为主键的模型,会在创建时自动生成 ID,因此只有在模型主键之外生成标识符时才需要直接调用 uuid7 或 ulid。