如果你之前通过 Laravel 内置的字符串函数处理过字符串的话,可能对 Laravel 中已存在的 Illuminate\Support\Str 类非常熟悉。Laravel 7 现在基于这些函数提供了一个更加面向对象的、更加流畅的字符串操作库。你可以使用 String::of 创建一个 Illuminate\Support\Stringable 对象,然后基于该对象提供的方法以链式的操作对字符串进行处理:

举例说明:

return (string) Str::of('  Laravel Framework 6.x ')
                ->trim()
                ->replace('6.x', '7.x')
                ->slug();

上面的代码,来自官网发行说明,我们很容易看到,每个方法都是干嘛的。

首先第一步将字符串 Laravel Framework 6.x 使用 Str::of() 方法进行包裹,之后我们就可以使用 Laravel 7 为我们提供的各种流畅的操作方法。

比如 trim() 去除前后空格。 replace() 进行替换,slug() 将字符串变成 slug 的形式

上面的代码实际运行结果就是:

laravel-framework-7x

上面的方法是不是用起来非常简单?

接下来我们介绍几个常用的方法。

before() 方法返回字符串中给定值之前的所有内容:

use Illuminate\Support\Str;

$slice = Str::of('This is my name')->before('my name');

// 'This is '

同理有 before(),就会有 after()

after() 方法返回字符串中给定值之后的所有内容。如果字符串中不存在该值,则将返回整个字符串:

 use Illuminate\Support\Str;

$slice = Str::of('This is my name')->after('This is');

// ' my name'

append() 方法将给定值附加到字符串:

use Illuminate\Support\Str;

$string = Str::of('Taylor')->append(' Otwell');

// 'Taylor Otwell'

lower() 方法将字符串转换为小写:

use Illuminate\Support\Str;

$result = Str::of('LARAVEL')->lower();

// 'laravel'

upper 函数将给定的字符串转换为大写:

use Illuminate\Support\Str;

$adjusted = Str::of('laravel')->upper();

// LARAVEL

title() 函数将给定的字符串转换为「首字母大写」:

use Illuminate\Support\Str;

$converted = Str::of('a nice title uses the correct case')->title();

// A Nice Title Uses The Correct Case

substr() 函数将给定的 start 和 length 参数指定的字符串部分:

use Illuminate\Support\Str;

$string = Str::of('Laravel Framework')->substr(8);

// Framework

$string = Str::of('Laravel Framework')->substr(8, 5);

// Frame

ucfirst() 函数将给定的字符串首字母大写:

use Illuminate\Support\Str;

$string = Str::of('foo bar')->ucfirst();

// Foo bar

words() 函数限制字符串中的单词数:

use Illuminate\Support\Str;

$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');

// Perfectly balanced, as >>>

length() 方法返回字符串的长度:

use Illuminate\Support\Str;

$length = Str::of('Laravel')->length();

// 7

ok,以上介绍了一些常用的方法,其实都是文档上的操作,我只不过那不过来操作演示一遍,更多的用法,请直接查看 文档

下面是 所有的方法集合

file

直接去 官方文档 进行查看。

关于极客返利

极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。

https://geekfl.com

https://geek.laravelcode.cn

版权许可

本作品采用 知识共享署名 4.0 国际许可协议 进行许可。

转载无需与我联系,但须注明出处,注明文章来源 Laravel 7 新特性-流畅的字符串操作

联系我

编程怪事
暂无回复
0 / 180