什么是 Str 类
Illuminate\Support\Str 类提供了丰富的字符串操作方法。相比逐个调用 PHP 标准字符串函数,它提供统一直观的接口。
Laravel 的字符串操作有两种风格:
- 静态方法风格:
Str::slug($title, '-'),适合单次操作 - Fluent 风格(方法链):
Str::of($title)->slug('-')->limit(50),可以把多个操作串起来
全局辅助函数
str() 与 Str::of() 等价。可以写 str('hello')->upper()。大小写与命名法转换
Str::camel() / Str::snake() / Str::kebab() / Str::studly()
Str::lower() / Str::upper() / Str::title()
Slug 与 URL
Str::slug() — 生成 URL 友好的 slug
用 Str::of() 一次完成生成与校验
字符串截断
Str::limit()
Str::words()
检索与判断
Str::contains()
Str::startsWith() / Str::endsWith()
Str::is() — 通配符匹配
变换与替换
Str::replace()
Str::replaceArray()
Str::replaceMatches() — 正则替换
Str::remove()
Str::squish()
前后操作
Str::before() / Str::after()
Str::between()
Str::start() / Str::finish()
若已经以该字符开头/结尾则不重复添加。
Str::chopStart() / Str::chopEnd()
脱敏与安全
Str::mask()
Str::excerpt()
随机字符串与标识符
Str::random()
Str::uuid() / Str::ulid()
Str::password()
Str::counted() — 数量与单复数
Fluent Strings(方法链)
以Str::of() 或 str() 开头会返回一个 Stringable 实例,支持方法链。最终转为字符串可用 (string) 强转或字符串上下文使用。
实用示例
博客文章 slug 生成条件方法链(when())
pipe()
Str::of() 常用方法
小结
常用 Str 方法一览
常用 Str 方法一览
静态方法 vs Fluent(Str::of)
静态方法 vs Fluent(Str::of)
静态方法适合:
- 只做 1~2 次变换
- 简洁易读
- 需要三次以上变换
- 含条件分支(
when()) - 希望以上下阅读的方式表达流程
Str 类 vs PHP 标准函数
Str 类 vs PHP 标准函数
使用
Str 类而不是 strtolower()、substr()、str_replace() 等:- 能安全处理多字节字符(内部使用
mb_*) - 方法链更聚合
- 参数顺序不再需要死记
- 保持 Laravel 代码风格一致