Laravel 13 字符串处理增强详解

摘要

Laravel 13 对字符串处理进行了增强,包括新的 Str 方法和 Stringable 链式操作。本文将深入讲解 Laravel 13 的字符串处理增强,包括:

  • Str 辅助函数
  • Stringable 链式操作
  • 字符串转换与格式化
  • 向量嵌入生成
  • 实战案例与最佳实践

本文适合希望掌握字符串处理技巧的 Laravel 开发者。

1. Str 辅助函数

1.1 基本操作

1
2
3
4
5
6
7
8
9
10
use Illuminate\Support\Str;

// 生成随机字符串
$random = Str::random(40);

// 生成 UUID
$uuid = Str::uuid();

// 生成有序 UUID
$orderedUuid = Str::orderedUuid();

1.2 字符串转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 驼峰命名
$camel = Str::camel('foo_bar'); // fooBar

// 蛇形命名
$snake = Str::snake('fooBar'); // foo_bar

// 短横线命名
$kebab = Str::kebab('fooBar'); // foo-bar

// Studly 命名
$studly = Str::studly('foo_bar'); // FooBar

// 标题格式
$title = Str::title('hello world'); // Hello World

1.3 字符串截取

1
2
3
4
5
6
7
8
// 限制长度
$limited = Str::limit('The quick brown fox', 10); // The quick...

// 限制单词
$words = Str::words('The quick brown fox', 2); // The quick...

// 截取
$substr = Str::substr('The quick brown fox', 4, 5); // quick

1.4 字符串替换

1
2
3
4
5
6
7
8
9
10
11
// 替换
$replaced = Str::replace('quick', 'slow', 'The quick brown fox');

// 替换首次
$replacedFirst = Str::replaceFirst('the', 'a', 'the quick the brown');

// 替换最后
$replacedLast = Str::replaceLast('the', 'a', 'the quick the brown');

// 替换数组
$replacedArray = Str::replaceArray('?', ['one', 'two'], '? and ?');

1.5 字符串检查

1
2
3
4
5
6
7
8
9
10
11
12
// 包含
Str::contains('The quick brown fox', 'quick'); // true
Str::contains('The quick brown fox', ['quick', 'slow']); // true

// 包含全部
Str::containsAll('The quick brown fox', ['quick', 'brown']); // true

// 开头
Str::startsWith('The quick brown fox', 'The'); // true

// 结尾
Str::endsWith('The quick brown fox', 'fox'); // true

2. Stringable 链式操作

2.1 创建 Stringable

1
2
3
4
5
6
use Illuminate\Support\Str;

$str = Str::of('The quick brown fox');

// 或使用辅助函数
$str = str('The quick brown fox');

2.2 链式调用

1
2
3
4
5
6
$result = Str::of('The quick brown fox')
->lower()
->replace('quick', 'slow')
->ucfirst()
->toString();
// The slow brown fox

2.3 常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 大小写转换
Str::of('hello')->upper(); // HELLO
Str::of('HELLO')->lower(); // hello
Str::of('hello')->ucfirst(); // Hello

// 去除空白
Str::of(' hello ')->trim(); // 'hello'
Str::of(' hello ')->ltrim(); // 'hello '
Str::of(' hello ')->rtrim(); // ' hello'

// 填充
Str::of('hello')->padLeft(10, '-'); // -----hello
Str::of('hello')->padRight(10, '-'); // hello-----

// 重复
Str::of('ab')->repeat(3); // ababab

2.4 高级操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 分割
$parts = Str::of('one, two, three')->explode(', ');
// ['one', 'two', 'three']

// 连接
$joined = Str::of(['a', 'b', 'c'])->join(', ', ' and ');
// a, b and c

// 分块
$chunks = Str::of('hello')->split(2);
// ['he', 'll', 'o']

// 正则匹配
$matches = Str::of('The quick brown fox')->match('/quick/');
// quick

// 正则替换
$replaced = Str::of('The quick brown fox')->replaceMatches('/quick/', 'slow');

3. 向量嵌入

3.1 生成嵌入

1
2
3
use Illuminate\Support\Str;

$embeddings = Str::of('Napa Valley has great wine.')->toEmbeddings();

3.2 批量生成

1
2
3
4
5
6
$texts = [
'The quick brown fox',
'jumps over the lazy dog',
];

$embeddings = Str::batchToEmbeddings($texts);

4. 文本处理

4.1 Markdown 处理```php

use Illuminate\Support\Str;

$html = Str::markdown(‘# Hello World’);
//

Hello World

$html = Str::of(‘# Hello World’)->markdown();

1
2
3
4
5
6
7
8
9
10
11

### 4.2 HTML 处理

```php
// 转义
$escaped = Str::of('<script>alert("XSS")</script>')->htmlEscape();
// &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

// 去除标签
$stripped = Str::of('<p>Hello</p>')->stripTags();
// Hello

4.3 Slug 生成

1
2
3
4
$slug = Str::slug('Laravel 13 Framework', '-');
// laravel-13-framework

$slug = Str::of('Laravel 13 Framework')->slug('-');

5. 密码处理

5.1 生成密码

1
2
3
4
5
6
use Illuminate\Support\Str;

$password = Str::password(12);
// 生成 12 位安全密码

$password = Str::password(12, letters: true, numbers: true, symbols: true);

5.2 掩码

1
2
3
4
5
$masked = Str::mask('john@example.com', '*', 3);
// joh************

$masked = Str::mask('1234567890', '*', -4);
// 123456****

6. 实战案例

6.1 文本处理管道

1
2
3
4
5
6
7
8
9
10
11
12
13
class TextProcessor
{
public function process(string $text): string
{
return Str::of($text)
->stripTags()
->trim()
->lower()
->replaceMatches('/\s+/', ' ')
->limit(200)
->toString();
}
}

6.2 SEO 友好 URL

1
2
3
4
5
6
7
8
9
10
11
12
class SlugGenerator
{
public function generate(string $title, int $id): string
{
return Str::of($title)
->lower()
->slug('-')
->limit(100)
->append("-{$id}")
->toString();
}
}

7. 最佳实践

7.1 使用链式调用

1
2
3
4
5
6
7
8
9
10
11
// 推荐:链式调用
$result = Str::of($text)
->trim()
->lower()
->replace(' ', '-')
->toString();

// 不推荐:多次调用
$text = trim($text);
$text = strtolower($text);
$text = str_replace(' ', '-', $text);

7.2 性能考虑

1
2
3
4
5
6
7
8
9
// 简单操作使用原生函数
$result = strtolower($text);

// 复杂操作使用 Stringable
$result = Str::of($text)
->lower()
->replace(' ', '-')
->limit(100)
->toString();

8. 总结

Laravel 13 的字符串处理提供了强大的功能:

  1. Str 辅助函数:丰富的字符串操作
  2. Stringable:优雅的链式调用
  3. 向量嵌入:AI 功能集成
  4. 文本处理:Markdown、HTML 等

参考资料