什么是 Str 类
Illuminate\Support\Str 类提供了丰富的字符串操作方法。相比逐个调用 PHP 标准字符串函数,它提供统一直观的接口。
Laravel 的字符串操作有两种风格:
静态方法风格 :Str::slug($title, '-'),适合单次操作
Fluent 风格(方法链) :Str::of($title)->slug('-')->limit(50),可以把多个操作串起来
use Illuminate\Support\ Str ;
// 静态方法
$slug = Str :: slug ( 'My New Blog Post' , '-' );
// 'my-new-blog-post'
// Fluent(Str::of)
$result = Str :: of ( ' My New Blog Post: Part 1 ' )
-> trim ()
-> slug ( '-' )
-> limit ( 30 );
全局辅助函数 str() 与 Str::of() 等价。可以写 str('hello')->upper()。
大小写与命名法转换
Str::camel() / Str::snake() / Str::kebab() / Str::studly()
use Illuminate\Support\ Str ;
Str :: camel ( 'foo_bar' ); // 'fooBar'
Str :: snake ( 'fooBar' ); // 'foo_bar'
Str :: kebab ( 'fooBar' ); // 'foo-bar'
Str :: studly ( 'foo_bar' ); // 'FooBar'
Str::lower() / Str::upper() / Str::title()
Str :: lower ( 'LARAVEL' ); // 'laravel'
Str :: upper ( 'laravel' ); // 'LARAVEL'
Str :: title ( 'hello world' ); // 'Hello World'
Slug 与 URL
Str::slug() — 生成 URL 友好的 slug
Str :: slug ( 'Laravel 框架' , '-' );
Str :: slug ( 'My New Blog Post' , '-' ); // 'my-new-blog-post'
Str :: slug ( 'Hello World!' , '_' ); // 'hello_world'
若包含非拉丁字符,slug 可能为空。可结合罗马字转换库,或使用 ID / 时间戳作为 URL。
用 Str::of() 一次完成生成与校验
$title = ' My New Blog Post: Part 1! ' ;
$slug = Str :: of ( $title )
-> trim ()
-> slug ( '-' )
-> limit ( 50 );
字符串截断
Str::limit()
$text = 'Laravel 是构建美观 Web 应用的 PHP 框架。' ;
Str :: limit ( $text , 20 );
Str :: limit ( $text , 20 , ' → 更多' );
Str :: limit ( 'The quick brown fox jumps over the lazy dog' , 20 , preserveWords : true );
Str::words()
Str :: words ( 'Perfectly balanced, as all things should be.' , 3 , ' >>>' );
// 'Perfectly balanced, as >>>'
检索与判断
Str::contains()
Str :: contains ( 'This is my name' , 'my' );
Str :: contains ( 'This is my name' , [ 'my' , 'your' ]);
Str :: contains ( 'This is my name' , 'MY' , ignoreCase : true );
Str::startsWith() / Str::endsWith()
Str :: startsWith ( 'https://laravel.com' , 'https://' );
Str :: endsWith ( 'photo.jpg' , '.jpg' );
Str :: endsWith ( 'photo.jpg' , [ '.jpg' , '.png' , '.gif' ]);
Str::is() — 通配符匹配
Str :: is ( 'foo*' , 'foobar' );
Str :: is ( '*/user/*' , '/admin/user/profile' );
Str :: is ( 'F*' , 'foo' , ignoreCase : true );
变换与替换
Str::replace()
Str :: replace ( '8.x' , '13.x' , 'Laravel 8.x' );
Str :: replace ( 'laravel' , 'Symphony' , 'I love Laravel' , caseSensitive : false );
Str::replaceArray()
Str :: replaceArray ( '?' , [ '上午 9 点' , '下午 5 点' ], '预约是 ? 到 ?' );
Str::replaceMatches() — 正则替换
Str :: replaceMatches ( '/[^0-9]/' , '' , '(03) 1234-5678' );
Str :: replaceMatches ( '/ \d + /' , fn ( $matches ) => '[' . $matches [ 0 ] . ']' , '1 个 2 只 3 支' );
Str::remove()
Str :: remove ( 'e' , 'Peter Piper picked a peck of pickled peppers.' );
Str :: remove ([ 'foo' , 'bar' ], 'foo and bar and baz' );
Str::squish()
Str :: squish ( ' Laravel Framework ' ); // 'Laravel Framework'
前后操作
Str::before() / Str::after()
Str :: before ( '[email protected] ' , '@' ); // 'test'
Str :: after ( '[email protected] ' , '@' ); // 'example.com'
Str :: afterLast ( 'App\Http\Controllers\UserController' , ' \\ ' ); // 'UserController'
Str :: beforeLast ( 'App\Http\Controllers\UserController' , ' \\ ' );
Str::between()
Str :: between ( '[debug] Error occurred in module' , '[' , ']' ); // 'debug'
Str::start() / Str::finish()
若已经以该字符开头/结尾则不重复添加。
Str :: start ( 'users/profile' , '/' ); // '/users/profile'
Str :: start ( '/users/profile' , '/' ); // '/users/profile'
Str :: finish ( 'https://example.com' , '/' ); // 'https://example.com/'
Str::chopStart() / Str::chopEnd()
Str :: chopStart ( 'https://laravel.com' , 'https://' );
Str :: chopStart ( 'http://laravel.com' , [ 'https://' , 'http://' ]);
Str :: chopEnd ( 'UserController.php' , '.php' );
脱敏与安全
Str::mask()
Str :: mask ( '[email protected] ' , '*' , 4 ); // 'yama**************'
Str :: mask ( '1234-5678-9012-3456' , '*' , - 4 ); // '***************3456'
Str :: mask ( '[email protected] ' , '*' , 3 , 5 ); // 'yam*****example.com'
Str::excerpt()
$text = 'Laravel 是构建美观 Web 应用的 PHP 框架。' ;
Str :: excerpt ( $text , 'PHP' , [ 'radius' => 10 ]);
随机字符串与标识符
Str::random()
Str::uuid() / Str::ulid()
( string ) Str :: uuid ();
( string ) Str :: uuid7 (); // 可按时间排序
( string ) Str :: ulid ();
Str::password()
Str::counted() — 数量与单复数
Str :: counted ( 'order' , 1 ); // '1 order'
Str :: counted ( 'order' , 1000 ); // '1,000 orders'
Str :: of ( 'order' ) -> counted ( 3 );
用于英文界面根据数量切换单复数时非常方便,逗号分隔的数字格式会自动应用。
Fluent Strings(方法链)
以 Str::of() 或 str() 开头会返回一个 Stringable 实例,支持方法链。最终转为字符串可用 (string) 强转或字符串上下文使用。
$result = Str :: of ( ' hello world ' )
-> trim ()
-> title ()
-> append ( '!' )
-> toString ();
实用示例
博客文章 slug 生成
$slug = Str :: of ( ' My New Blog Post: Part 1 ' )
-> trim ()
-> lower ()
-> slug ( '-' )
-> limit ( 50 );
从 URL 中提取域名
$domain = Str :: of ( 'https://www.example.com/path/to/page' )
-> after ( '//' )
-> before ( '/' )
-> chopStart ( 'www.' );
// 'example.com'
用户输入清洗
$clean = Str :: of ( $userInput )
-> squish ()
-> limit ( 255 )
-> toString ();
从类名生成文件路径
$path = Str :: of ( 'App\Http\Controllers\UserController' )
-> replace ( ' \\ ' , '/' )
-> append ( '.php' )
-> toString ();
条件方法链(when())
$result = Str :: of ( 'Laravel' )
-> when ( $isUppercase , fn ( $str ) => $str -> upper ())
-> append ( ' Framework' );
pipe()
$result = Str :: of ( 'my-slug' )
-> pipe ( fn ( $str ) => $str -> replace ( '-' , '_' ))
-> upper ()
-> toString ();
Str::of() 常用方法
$str = Str :: of ( 'Hello, World!' );
$str -> length ();
$str -> upper ();
$str -> lower ();
$str -> trim ();
$str -> slug ();
$str -> camel ();
$str -> contains ( 'World' );
$str -> startsWith ( 'Hello' );
$str -> endsWith ( '!' );
$str -> replace ( ',' , '' );
$str -> prepend ( '>>> ' );
$str -> append ( ' <<<' );
$str -> reverse ();
$str -> wordCount ();
方法 用途 Str::slug($str)生成 URL 友好的 slug Str::limit($str, $n)按字符截断 Str::contains($str, $needle)判断是否包含 Str::startsWith($str, $needle)判断是否以 needle 开头 Str::endsWith($str, $needle)判断是否以 needle 结尾 Str::replace($search, $replace, $str)替换 Str::camel($str)camelCase Str::snake($str)snake_case Str::kebab($str)kebab-case Str::studly($str)StudlyCase Str::upper($str)大写 Str::lower($str)小写 Str::squish($str)压缩空白 Str::after($str, $search)取 search 之后 Str::before($str, $search)取 search 之前 Str::between($str, $from, $to)取两串之间 Str::mask($str, '*', $index)脱敏 Str::random($length)随机字符串 Str::uuid()UUID Str::of($str)Fluent 起点
静态方法适合 :Fluent 适合 :
需要三次以上变换
含条件分支(when())
希望以上下阅读的方式表达流程
使用 Str 类而不是 strtolower()、substr()、str_replace() 等:
能安全处理多字节字符(内部使用 mb_*)
方法链更聚合
参数顺序不再需要死记
保持 Laravel 代码风格一致