Skip to content

字符串

简介

Laravel 包含大量用于操作字符串值的函数。其中许多函数被框架本身使用;但是,如果你觉得方便,也可以在自己的应用程序中自由使用它们。

可用方法

字符串

流式字符串

字符串

__()

__ 函数会使用你的语言文件来翻译给定的翻译字符串或翻译键:

php
echo __('Welcome to our application');

echo __('messages.welcome');

如果指定的翻译字符串或键不存在,__ 函数将返回给定的值。因此,使用上面的示例时,如果该翻译键不存在,__ 函数会返回 messages.welcome

class_basename()

class_basename 函数会返回给定类的类名,并移除其命名空间:

php
$class = class_basename('Foo\Bar\Baz');

// Baz

e()

e 函数会调用 PHP 的 htmlspecialchars 函数,并默认将 double_encode 选项设为 true

php
echo e('<html>foo</html>');

// &lt;html&gt;foo&lt;/html&gt;

preg_replace_array()

preg_replace_array 函数会使用数组按顺序替换字符串中匹配给定模式的内容:

php
$string = 'The event will take place between :start and :end';

$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);

// The event will take place between 8:30 and 9:00

Str::after()

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

php
use Illuminate\Support\Str;

$slice = Str::after('This is my name', 'This is');

// ' my name'

Str::afterLast()

Str::afterLast 方法会返回字符串中最后一次出现给定值之后的所有内容。如果该值不存在于字符串中,则返回整个字符串:

php
use Illuminate\Support\Str;

$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');

// 'Controller'

Str::apa()

Str::apa 方法会按照 APA 规范将给定字符串转换为标题格式:

php
use Illuminate\Support\Str;

$title = Str::apa('Creating A Project');

// 'Creating a Project'

Str::ascii()

Str::ascii 方法会尝试将字符串转写为 ASCII 值:

php
use Illuminate\Support\Str;

$slice = Str::ascii('û');

// 'u'

Str::before()

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

php
use Illuminate\Support\Str;

$slice = Str::before('This is my name', 'my name');

// 'This is '

Str::beforeLast()

Str::beforeLast 方法会返回字符串中最后一次出现给定值之前的所有内容:

php
use Illuminate\Support\Str;

$slice = Str::beforeLast('This is my name', 'is');

// 'This '

Str::between()

Str::between 方法会返回字符串中两个值之间的部分:

php
use Illuminate\Support\Str;

$slice = Str::between('This is my name', 'This', 'name');

// ' is my '

Str::betweenFirst()

Str::betweenFirst 方法会返回字符串中两个值之间最短的那一段内容:

php
use Illuminate\Support\Str;

$slice = Str::betweenFirst('[a] bc [d]', '[', ']');

// 'a'

Str::camel()

Str::camel 方法会将给定字符串转换为 camelCase

php
use Illuminate\Support\Str;

$converted = Str::camel('foo_bar');

// 'fooBar'

Str::charAt()

Str::charAt 方法会返回指定索引位置的字符。如果索引越界,则返回 false

php
use Illuminate\Support\Str;

$character = Str::charAt('This is my name.', 6);

// 's'

Str::chopStart()

Str::chopStart 方法仅在给定值出现在字符串开头时,移除它的第一次出现:

php
use Illuminate\Support\Str;

$url = Str::chopStart('https://laravel.com', 'https://');

// 'laravel.com'

你也可以将数组作为第二个参数传入。如果字符串以数组中的任意一个值开头,则会从字符串中移除该值:

php
use Illuminate\Support\Str;

$url = Str::chopStart('http://laravel.com', ['https://', 'http://']);

// 'laravel.com'

Str::chopEnd()

Str::chopEnd 方法仅在给定值出现在字符串末尾时,移除它的最后一次出现:

php
use Illuminate\Support\Str;

$url = Str::chopEnd('app/Models/Photograph.php', '.php');

// 'app/Models/Photograph'

你也可以将数组作为第二个参数传入。如果字符串以数组中的任意一个值结尾,则会从字符串中移除该值:

php
use Illuminate\Support\Str;

$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);

// 'laravel.com'

Str::contains()

Str::contains 方法会判断给定字符串是否包含指定值。默认情况下,此方法区分大小写:

php
use Illuminate\Support\Str;

$contains = Str::contains('This is my name', 'my');

// true

你也可以传入一个值数组,以判断给定字符串是否包含数组中的任意一个值:

php
use Illuminate\Support\Str;

$contains = Str::contains('This is my name', ['my', 'foo']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$contains = Str::contains('This is my name', 'MY', ignoreCase: true);

// true

Str::containsAll()

Str::containsAll 方法会判断给定字符串是否包含给定数组中的所有值:

php
use Illuminate\Support\Str;

$containsAll = Str::containsAll('This is my name', ['my', 'name']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$containsAll = Str::containsAll('This is my name', ['MY', 'NAME'], ignoreCase: true);

// true

Str::doesntContain()

Str::doesntContain 方法会判断给定字符串是否不包含指定值。默认情况下,此方法区分大小写:

php
use Illuminate\Support\Str;

$doesntContain = Str::doesntContain('This is name', 'my');

// true

你也可以传入一个值数组,以判断给定字符串是否不包含数组中的任何值:

php
use Illuminate\Support\Str;

$doesntContain = Str::doesntContain('This is name', ['my', 'framework']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$doesntContain = Str::doesntContain('This is name', 'MY', ignoreCase: true);

// true

Str::deduplicate()

Str::deduplicate 方法会将给定字符串中连续重复的某个字符替换为单个字符。默认情况下,该方法会去重空格:

php
use Illuminate\Support\Str;

$result = Str::deduplicate('The   Laravel   Framework');

// The Laravel Framework

你可以通过将不同的字符作为第二个参数传入,指定要去重的字符:

php
use Illuminate\Support\Str;

$result = Str::deduplicate('The---Laravel---Framework', '-');

// The-Laravel-Framework

Str::doesntEndWith()

Str::doesntEndWith 方法会判断给定字符串是否不以指定值结尾:

php
use Illuminate\Support\Str;

$result = Str::doesntEndWith('This is my name', 'dog');

// true

你也可以传入一个值数组,以判断给定字符串是否不以数组中的任何一个值结尾:

php
use Illuminate\Support\Str;

$result = Str::doesntEndWith('This is my name', ['this', 'foo']);

// true

$result = Str::doesntEndWith('This is my name', ['name', 'foo']);

// false

Str::doesntStartWith()

Str::doesntStartWith 方法会判断给定字符串是否不以指定值开头:

php
use Illuminate\Support\Str;

$result = Str::doesntStartWith('This is my name', 'That');

// true

如果传入的是可能值数组,那么当字符串不以这些给定值中的任何一个开头时,doesntStartWith 方法会返回 true

php
$result = Str::doesntStartWith('This is my name', ['What', 'That', 'There']);

// true

Str::endsWith()

Str::endsWith 方法会判断给定字符串是否以指定值结尾:

php
use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', 'name');

// true

你也可以传入一个值数组,以判断给定字符串是否以数组中的任意一个值结尾:

php
use Illuminate\Support\Str;

$result = Str::endsWith('This is my name', ['name', 'foo']);

// true

$result = Str::endsWith('This is my name', ['this', 'foo']);

// false

Str::excerpt()

Str::excerpt 方法会从给定字符串中提取包含某个短语首次匹配位置的摘要:

php
use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'my', [
    'radius' => 3
]);

// '...is my na...'

radius 选项默认值为 100,用于定义截断字符串两侧应显示的字符数。

此外,你可以使用 omission 选项来定义追加到截断字符串前后的字符串:

php
use Illuminate\Support\Str;

$excerpt = Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]);

// '(...) my name'

Str::finish()

Str::finish 方法会在字符串尚未以给定值结尾时,为其追加一个该值:

php
use Illuminate\Support\Str;

$adjusted = Str::finish('this/string', '/');

// this/string/

$adjusted = Str::finish('this/string/', '/');

// this/string/

Str::fromBase64()

Str::fromBase64 方法会解码给定的 Base64 字符串:

php
use Illuminate\Support\Str;

$decoded = Str::fromBase64('TGFyYXZlbA==');

// Laravel

Str::headline()

Str::headline 方法会将按大小写、连字符或下划线分隔的字符串转换为空格分隔,并将每个单词首字母大写的字符串:

php
use Illuminate\Support\Str;

$headline = Str::headline('steve_jobs');

// Steve Jobs

$headline = Str::headline('EmailNotificationSent');

// Email Notification Sent

Str::initials()

Str::initials 方法会返回给定字符串的首字母缩写,并可选择将其转为大写:

php
use Illuminate\Support\Str;

$initials = Str::initials('taylor otwell');

// to

$initials = Str::initials('taylor otwell', capitalize: true);

// TO

Str::inlineMarkdown()

Str::inlineMarkdown 方法会使用 CommonMark 将 GitHub 风格 Markdown 转换为内联 HTML。不过,与 markdown 方法不同的是,它不会将生成的 HTML 包裹在块级元素中:

php
use Illuminate\Support\Str;

$html = Str::inlineMarkdown('**Laravel**');

// <strong>Laravel</strong>

Markdown 安全性

默认情况下,Markdown 支持原始 HTML,这在处理原始用户输入时会带来跨站脚本攻击(XSS)漏洞。根据 CommonMark 安全文档,你可以使用 html_input 选项对原始 HTML 进行转义或剥离,并通过 allow_unsafe_links 选项指定是否允许不安全链接。如果你需要允许部分原始 HTML,应当将编译后的 Markdown 再交给 HTML Purifier 处理:

php
use Illuminate\Support\Str;

Str::inlineMarkdown('Inject: <script>alert("Hello XSS!");</script>', [
    'html_input' => 'strip',
    'allow_unsafe_links' => false,
]);

// Inject: alert(&quot;Hello XSS!&quot;);

Str::is()

Str::is 方法会判断给定字符串是否匹配指定模式。星号可用作通配符:

php
use Illuminate\Support\Str;

$matches = Str::is('foo*', 'foobar');

// true

$matches = Str::is('baz*', 'foobar');

// false

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$matches = Str::is('*.jpg', 'photo.JPG', ignoreCase: true);

// true

Str::isAscii()

Str::isAscii 方法会判断给定字符串是否为 7 位 ASCII:

php
use Illuminate\Support\Str;

$isAscii = Str::isAscii('Taylor');

// true

$isAscii = Str::isAscii('ü');

// false

Str::isJson()

Str::isJson 方法会判断给定字符串是否为有效的 JSON:

php
use Illuminate\Support\Str;

$result = Str::isJson('[1,2,3]');

// true

$result = Str::isJson('{"first": "John", "last": "Doe"}');

// true

$result = Str::isJson('{first: "John", last: "Doe"}');

// false

Str::isUrl()

Str::isUrl 方法会判断给定字符串是否为有效的 URL:

php
use Illuminate\Support\Str;

$isUrl = Str::isUrl('http://example.com');

// true

$isUrl = Str::isUrl('laravel');

// false

isUrl 方法默认会将多种协议视为有效。不过,你也可以将允许的协议传给 isUrl 方法,以明确指定哪些协议应被视为有效:

php
$isUrl = Str::isUrl('http://example.com', ['http', 'https']);

Str::isUlid()

Str::isUlid 方法会判断给定字符串是否为有效的 ULID:

php
use Illuminate\Support\Str;

$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');

// true

$isUlid = Str::isUlid('laravel');

// false

Str::isUuid()

Str::isUuid 方法会判断给定字符串是否为有效的 UUID:

php
use Illuminate\Support\Str;

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');

// true

$isUuid = Str::isUuid('laravel');

// false

你还可以校验给定 UUID 是否符合指定版本(1、3、4、5、6、7 或 8)的 UUID 规范:

php
use Illuminate\Support\Str;

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 4);

// true

$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', version: 1);

// false

Str::kebab()

Str::kebab 方法会将给定字符串转换为 kebab-case

php
use Illuminate\Support\Str;

$converted = Str::kebab('fooBar');

// foo-bar

Str::lcfirst()

Str::lcfirst 方法会返回将首字符转为小写后的字符串:

php
use Illuminate\Support\Str;

$string = Str::lcfirst('Foo Bar');

// foo Bar

Str::length()

Str::length 方法会返回给定字符串的长度:

php
use Illuminate\Support\Str;

$length = Str::length('Laravel');

// 7

Str::limit()

Str::limit 方法会将给定字符串截断为指定长度:

php
use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox...

你可以向该方法传入第三个参数,以修改追加到截断字符串末尾的内容:

php
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

如果你希望在截断字符串时保留完整单词,可以使用 preserveWords 参数。当该参数为 true 时,字符串会在最近的完整单词边界处被截断:

php
$truncated = Str::limit('The quick brown fox', 12, preserveWords: true);

// The quick...

Str::lower()

Str::lower 方法会将给定字符串转换为小写:

php
use Illuminate\Support\Str;

$converted = Str::lower('LARAVEL');

// laravel

Str::markdown()

Str::markdown 方法会使用 CommonMark 将 GitHub 风格 Markdown 转换为 HTML:

php
use Illuminate\Support\Str;

$html = Str::markdown('# Laravel');

// <h1>Laravel</h1>

$html = Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]);

// <h1>Taylor Otwell</h1>

Markdown 安全性

默认情况下,Markdown 支持原始 HTML,这在处理原始用户输入时会带来跨站脚本攻击(XSS)漏洞。根据 CommonMark 安全文档,你可以使用 html_input 选项对原始 HTML 进行转义或剥离,并通过 allow_unsafe_links 选项指定是否允许不安全链接。如果你需要允许部分原始 HTML,应当将编译后的 Markdown 再交给 HTML Purifier 处理:

php
use Illuminate\Support\Str;

Str::markdown('Inject: <script>alert("Hello XSS!");</script>', [
    'html_input' => 'strip',
    'allow_unsafe_links' => false,
]);

// <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

Str::mask()

Str::mask 方法会使用重复字符遮罩字符串中的一部分,可用于模糊处理电子邮件地址、电话号码等字符串片段:

php
use Illuminate\Support\Str;

$string = Str::mask('taylor@example.com', '*', 3);

// tay***************

如果需要,你可以将负数作为 mask 方法的第三个参数传入,这会让该方法从距离字符串末尾指定距离的位置开始进行遮罩:

php
$string = Str::mask('taylor@example.com', '*', -15, 3);

// tay***@example.com

Str::match()

Str::match 方法会返回字符串中匹配给定正则表达式模式的部分:

php
use Illuminate\Support\Str;

$result = Str::match('/bar/', 'foo bar');

// 'bar'

$result = Str::match('/foo (.*)/', 'foo bar');

// 'bar'

Str::matchAll()

Str::matchAll 方法会返回一个 collection,其中包含字符串中匹配给定正则表达式模式的所有部分:

php
use Illuminate\Support\Str;

$result = Str::matchAll('/bar/', 'bar foo bar');

// collect(['bar', 'bar'])

如果你在表达式中指定了匹配组,Laravel 将返回一个 collection,其中包含第一个匹配组的匹配结果:

php
use Illuminate\Support\Str;

$result = Str::matchAll('/f(\w*)/', 'bar fun bar fly');

// collect(['un', 'ly']);

如果没有找到匹配项,将返回一个空的 collection。

Str::isMatch()

如果字符串匹配给定正则表达式,Str::isMatch 方法将返回 true

php
use Illuminate\Support\Str;

$result = Str::isMatch('/foo (.*)/', 'foo bar');

// true

$result = Str::isMatch('/foo (.*)/', 'laravel');

// false

Str::orderedUuid()

Str::orderedUuid 方法会生成一个“时间戳优先”的 UUID,便于高效存储在带索引的数据库列中。使用该方法生成的每个 UUID 都会排在之前生成的 UUID 之后:

php
use Illuminate\Support\Str;

return (string) Str::orderedUuid();

Str::padBoth()

Str::padBoth 方法封装了 PHP 的 str_pad 函数,会在字符串两侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::padBoth('James', 10, '_');

// '__James___'

$padded = Str::padBoth('James', 10);

// '  James   '

Str::padLeft()

Str::padLeft 方法封装了 PHP 的 str_pad 函数,会在字符串左侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::padLeft('James', 10, '-=');

// '-=-=-James'

$padded = Str::padLeft('James', 10);

// '     James'

Str::padRight()

Str::padRight 方法封装了 PHP 的 str_pad 函数,会在字符串右侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::padRight('James', 10, '-');

// 'James-----'

$padded = Str::padRight('James', 10);

// 'James     '

Str::password()

Str::password 方法可用于生成指定长度的安全随机密码。密码由字母、数字、符号和空格组合而成。默认长度为 32 个字符:

php
use Illuminate\Support\Str;

$password = Str::password();

// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'

$password = Str::password(12);

// 'qwuar>#V|i]N'

Str::plural()

Str::plural 方法会将单数单词字符串转换为复数形式。此函数支持 Laravel 复数化器支持的所有语言

php
use Illuminate\Support\Str;

$plural = Str::plural('car');

// cars

$plural = Str::plural('child');

// children

你可以向该函数传入一个整数作为第二个参数,以获取字符串的单数或复数形式:

php
use Illuminate\Support\Str;

$plural = Str::plural('child', 2);

// children

$singular = Str::plural('child', 1);

// child

你可以提供 prependCount 参数,以便在复数化后的字符串前加上格式化后的 $count

php
use Illuminate\Support\Str;

$label = Str::plural('car', 1000, prependCount: true);

// 1,000 cars

Str::pluralStudly()

Str::pluralStudly 方法会将采用 studly caps 格式的单数单词字符串转换为复数形式。此函数支持 Laravel 复数化器支持的所有语言

php
use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman');

// VerifiedHumans

$plural = Str::pluralStudly('UserFeedback');

// UserFeedback

你可以向该函数传入一个整数作为第二个参数,以获取字符串的单数或复数形式:

php
use Illuminate\Support\Str;

$plural = Str::pluralStudly('VerifiedHuman', 2);

// VerifiedHumans

$singular = Str::pluralStudly('VerifiedHuman', 1);

// VerifiedHuman

Str::position()

Str::position 方法会返回子字符串在字符串中首次出现的位置。如果子字符串不存在于给定字符串中,则返回 false

php
use Illuminate\Support\Str;

$position = Str::position('Hello, World!', 'Hello');

// 0

$position = Str::position('Hello, World!', 'W');

// 7

Str::random()

Str::random 方法会生成指定长度的随机字符串。该函数使用 PHP 的 random_bytes 函数:

php
use Illuminate\Support\Str;

$random = Str::random(40);

在测试期间,伪造 Str::random 方法返回的值可能会很有用。要实现这一点,你可以使用 createRandomStringsUsing 方法:

php
Str::createRandomStringsUsing(function () {
    return 'fake-random-string';
});

如果你希望 random 方法恢复正常生成随机字符串,可以调用 createRandomStringsNormally 方法:

php
Str::createRandomStringsNormally();

Str::remove()

Str::remove 方法会从字符串中移除给定值或值数组:

php
use Illuminate\Support\Str;

$string = 'Peter Piper picked a peck of pickled peppers.';

$removed = Str::remove('e', $string);

// Ptr Pipr pickd a pck of pickld ppprs.

你也可以将 false 作为第三个参数传给 remove 方法,以在移除字符串时忽略大小写。

Str::repeat()

Str::repeat 方法会重复给定字符串:

php
use Illuminate\Support\Str;

$string = 'a';

$repeat = Str::repeat($string, 5);

// aaaaa

Str::replace()

Str::replace 方法会替换字符串中的指定内容:

php
use Illuminate\Support\Str;

$string = 'Laravel 11.x';

$replaced = Str::replace('11.x', '12.x', $string);

// Laravel 12.x

replace 方法还接受一个 caseSensitive 参数。默认情况下,replace 方法区分大小写:

php
$replaced = Str::replace(
    'php',
    'Laravel',
    'PHP Framework for Web Artisans',
    caseSensitive: false
);

// Laravel Framework for Web Artisans

Str::replaceArray()

Str::replaceArray 方法会使用数组按顺序替换字符串中的给定值:

php
use Illuminate\Support\Str;

$string = 'The event will take place between ? and ?';

$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);

// The event will take place between 8:30 and 9:00

Str::replaceFirst()

Str::replaceFirst 方法会替换字符串中给定值的第一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');

// a quick brown fox jumps over the lazy dog

Str::replaceLast()

Str::replaceLast 方法会替换字符串中给定值的最后一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');

// the quick brown fox jumps over a lazy dog

Str::replaceMatches()

Str::replaceMatches 方法会将字符串中所有匹配某个模式的部分替换为给定的替换字符串:

php
use Illuminate\Support\Str;

$replaced = Str::replaceMatches(
    pattern: '/[^A-Za-z0-9]++/',
    replace: '',
    subject: '(+1) 501-555-1000'
)

// '15015551000'

replaceMatches 方法还接受一个 closure,它会针对字符串中每个匹配给定模式的部分被调用,让你可以在 closure 中执行替换逻辑并返回替换后的值:

php
use Illuminate\Support\Str;

$replaced = Str::replaceMatches('/\d/', function (array $matches) {
    return '['.$matches[0].']';
}, '123');

// '[1][2][3]'

Str::replaceStart()

Str::replaceStart 方法仅在给定值出现在字符串开头时,替换它的第一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');

// Laravel World

$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');

// Hello World

Str::replaceEnd()

Str::replaceEnd 方法仅在给定值出现在字符串末尾时,替换它的最后一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World');

// Hello Laravel

$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World');

// Hello World

Str::reverse()

Str::reverse 方法会反转给定字符串:

php
use Illuminate\Support\Str;

$reversed = Str::reverse('Hello World');

// dlroW olleH

Str::singular()

Str::singular 方法会将字符串转换为单数形式。此函数支持 Laravel 复数化器支持的所有语言

php
use Illuminate\Support\Str;

$singular = Str::singular('cars');

// car

$singular = Str::singular('children');

// child

Str::slug()

Str::slug 方法会根据给定字符串生成对 URL 友好的 “slug”:

php
use Illuminate\Support\Str;

$slug = Str::slug('Laravel 5 Framework', '-');

// laravel-5-framework

Str::snake()

Str::snake 方法会将给定字符串转换为 snake_case

php
use Illuminate\Support\Str;

$converted = Str::snake('fooBar');

// foo_bar

$converted = Str::snake('fooBar', '-');

// foo-bar

Str::squish()

Str::squish 方法会移除字符串中的所有多余空白,包括单词之间多余的空白:

php
use Illuminate\Support\Str;

$string = Str::squish('    laravel    framework    ');

// laravel framework

Str::start()

Str::start 方法会在字符串尚未以给定值开头时,为其添加一个该值:

php
use Illuminate\Support\Str;

$adjusted = Str::start('this/string', '/');

// /this/string

$adjusted = Str::start('/this/string', '/');

// /this/string

Str::startsWith()

Str::startsWith 方法会判断给定字符串是否以指定值开头:

php
use Illuminate\Support\Str;

$result = Str::startsWith('This is my name', 'This');

// true

如果传入的是可能值数组,那么当字符串以这些给定值中的任意一个开头时,startsWith 方法会返回 true

php
$result = Str::startsWith('This is my name', ['This', 'That', 'There']);

// true

Str::studly()

Str::studly 方法会将给定字符串转换为 StudlyCase

php
use Illuminate\Support\Str;

$converted = Str::studly('foo_bar');

// FooBar

Str::substr()

Str::substr 方法会返回由起始位置和长度参数指定的字符串片段:

php
use Illuminate\Support\Str;

$converted = Str::substr('The Laravel Framework', 4, 7);

// Laravel

Str::substrCount()

Str::substrCount 方法会返回给定字符串中指定值出现的次数:

php
use Illuminate\Support\Str;

$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');

// 2

Str::substrReplace()

Str::substrReplace 方法会替换字符串某一部分中的文本,起始位置由第三个参数指定,替换字符数由第四个参数指定。如果将第四个参数设为 0,则会在指定位置插入字符串,而不会替换字符串中现有的任何字符:

php
use Illuminate\Support\Str;

$result = Str::substrReplace('1300', ':', 2);
// 13:

$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00

Str::swap()

Str::swap 方法会使用 PHP 的 strtr 函数替换给定字符串中的多个值:

php
use Illuminate\Support\Str;

$string = Str::swap([
    'Tacos' => 'Burritos',
    'great' => 'fantastic',
], 'Tacos are great!');

// Burritos are fantastic!

Str::take()

Str::take 方法会从字符串开头返回指定数量的字符:

php
use Illuminate\Support\Str;

$taken = Str::take('Build something amazing!', 5);

// Build

Str::title()

Str::title 方法会将给定字符串转换为 Title Case

php
use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

Str::toBase64()

Str::toBase64 方法会将给定字符串转换为 Base64:

php
use Illuminate\Support\Str;

$base64 = Str::toBase64('Laravel');

// TGFyYXZlbA==

Str::transliterate()

Str::transliterate 方法会尝试将给定字符串转换为最接近的 ASCII 表示:

php
use Illuminate\Support\Str;

$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');

// 'test@laravel.com'

Str::trim()

Str::trim 方法会移除给定字符串开头和结尾的空白(或其他字符)。与 PHP 原生的 trim 函数不同,Str::trim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

$string = Str::trim(' foo bar ');

// 'foo bar'

Str::ltrim()

Str::ltrim 方法会移除给定字符串开头的空白(或其他字符)。与 PHP 原生的 ltrim 函数不同,Str::ltrim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

$string = Str::ltrim('  foo bar  ');

// 'foo bar  '

Str::rtrim()

Str::rtrim 方法会移除给定字符串末尾的空白(或其他字符)。与 PHP 原生的 rtrim 函数不同,Str::rtrim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

$string = Str::rtrim('  foo bar  ');

// '  foo bar'

Str::ucfirst()

Str::ucfirst 方法会返回首字符大写后的字符串:

php
use Illuminate\Support\Str;

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

// Foo bar

Str::ucsplit()

Str::ucsplit 方法会按大写字符将给定字符串拆分为数组:

php
use Illuminate\Support\Str;

$segments = Str::ucsplit('FooBar');

// [0 => 'Foo', 1 => 'Bar']

Str::ucwords()

Str::ucwords 方法会将给定字符串中每个单词的首字符转换为大写:

php
use Illuminate\Support\Str;

$string = Str::ucwords('laravel framework');

// Laravel Framework

Str::upper()

Str::upper 方法会将给定字符串转换为大写:

php
use Illuminate\Support\Str;

$string = Str::upper('laravel');

// LARAVEL

Str::ulid()

Str::ulid 方法会生成一个 ULID,它是一种紧凑的、按时间排序的唯一标识符:

php
use Illuminate\Support\Str;

return (string) Str::ulid();

// 01gd6r360bp37zj17nxb55yv40

如果你想获取一个表示给定 ULID 创建日期和时间的 Illuminate\Support\Carbon 日期实例,可以使用 Laravel Carbon 集成提供的 createFromId 方法:

php
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

$date = Carbon::createFromId((string) Str::ulid());

在测试期间,伪造 Str::ulid 方法返回的值可能会很有用。要实现这一点,你可以使用 createUlidsUsing 方法:

php
use Symfony\Component\Uid\Ulid;

Str::createUlidsUsing(function () {
    return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});

如果你希望 ulid 方法恢复正常生成 ULID,可以调用 createUlidsNormally 方法:

php
Str::createUlidsNormally();

Str::unwrap()

Str::unwrap 方法会从给定字符串的开头和结尾移除指定字符串:

php
use Illuminate\Support\Str;

Str::unwrap('-Laravel-', '-');

// Laravel

Str::unwrap('{framework: "Laravel"}', '{', '}');

// framework: "Laravel"

Str::uuid()

Str::uuid 方法会生成一个 UUID(版本 4):

php
use Illuminate\Support\Str;

return (string) Str::uuid();

在测试期间,伪造 Str::uuid 方法返回的值可能会很有用。要实现这一点,你可以使用 createUuidsUsing 方法:

php
use Ramsey\Uuid\Uuid;

Str::createUuidsUsing(function () {
    return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');
});

如果你希望 uuid 方法恢复正常生成 UUID,可以调用 createUuidsNormally 方法:

php
Str::createUuidsNormally();

Str::uuid7()

Str::uuid7 方法会生成一个 UUID(版本 7):

php
use Illuminate\Support\Str;

return (string) Str::uuid7();

你可以传入一个 DateTimeInterface 作为可选参数,它将用于生成有序 UUID:

php
return (string) Str::uuid7(time: now());

Str::wordCount()

Str::wordCount 方法会返回字符串包含的单词数量:

php
use Illuminate\Support\Str;

Str::wordCount('Hello, world!'); // 2

Str::wordWrap()

Str::wordWrap 方法会按给定字符数对字符串进行换行包装:

php
use Illuminate\Support\Str;

$text = "The quick brown fox jumped over the lazy dog."

Str::wordWrap($text, characters: 20, break: "<br />\n");

/*
The quick brown fox<br />
jumped over the lazy<br />
dog.
*/

Str::words()

Str::words 方法会限制字符串中的单词数量。你可以通过第三个参数传入一个附加字符串,用于指定应追加到截断字符串末尾的内容:

php
use Illuminate\Support\Str;

return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');

// Perfectly balanced, as >>>

Str::wrap()

Str::wrap 方法会使用另一个字符串或一对字符串包裹给定字符串:

php
use Illuminate\Support\Str;

Str::wrap('Laravel', '"');

// "Laravel"

Str::wrap('is', before: 'This ', after: ' Laravel!');

// This is Laravel!

str()

str 函数会返回给定字符串对应的一个新的 Illuminate\Support\Stringable 实例。此函数等价于 Str::of 方法:

php
$string = str('Taylor')->append(' Otwell');

// 'Taylor Otwell'

如果没有向 str 函数提供参数,该函数将返回一个 Illuminate\Support\Str 实例:

php
$snake = str()->snake('FooBar');

// 'foo_bar'

trans()

trans 函数会使用你的语言文件来翻译给定的翻译键:

php
echo trans('messages.welcome');

如果指定的翻译键不存在,trans 函数将返回给定的键。因此,使用上面的示例时,如果该翻译键不存在,trans 函数会返回 messages.welcome

trans_choice()

trans_choice 函数会根据单复数变化翻译给定的翻译键:

php
echo trans_choice('messages.notifications', $unreadCount);

如果指定的翻译键不存在,trans_choice 函数将返回给定的键。因此,使用上面的示例时,如果该翻译键不存在,trans_choice 函数会返回 messages.notifications

流式字符串

流式字符串提供了一种更流畅的、面向对象的接口来处理字符串值,允许你使用比传统字符串操作更可读的语法将多个字符串操作链式调用在一起。

after

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

php
use Illuminate\Support\Str;

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

// ' my name'

afterLast

afterLast 方法会返回字符串中最后一次出现给定值之后的所有内容。如果该值不存在于字符串中,则返回整个字符串:

php
use Illuminate\Support\Str;

$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');

// 'Controller'

apa

apa 方法会按照 APA 规范将给定字符串转换为标题格式:

php
use Illuminate\Support\Str;

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

// A Nice Title Uses the Correct Case

append

append 方法会将给定值追加到字符串末尾:

php
use Illuminate\Support\Str;

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

// 'Taylor Otwell'

ascii

ascii 方法会尝试将字符串转写为 ASCII 值:

php
use Illuminate\Support\Str;

$string = Str::of('ü')->ascii();

// 'u'

basename

basename 方法会返回给定字符串末尾的名称部分:

php
use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->basename();

// 'baz'

如果需要,你可以提供一个将从末尾组件中移除的“扩展名”:

php
use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');

// 'baz'

before

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

php
use Illuminate\Support\Str;

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

// 'This is '

beforeLast

beforeLast 方法会返回字符串中最后一次出现给定值之前的所有内容:

php
use Illuminate\Support\Str;

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

// 'This '

between

between 方法会返回字符串中两个值之间的部分:

php
use Illuminate\Support\Str;

$converted = Str::of('This is my name')->between('This', 'name');

// ' is my '

betweenFirst

betweenFirst 方法会返回字符串中两个值之间最短的那一段内容:

php
use Illuminate\Support\Str;

$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');

// 'a'

camel

camel 方法会将给定字符串转换为 camelCase

php
use Illuminate\Support\Str;

$converted = Str::of('foo_bar')->camel();

// 'fooBar'

charAt

charAt 方法会返回指定索引位置的字符。如果索引越界,则返回 false

php
use Illuminate\Support\Str;

$character = Str::of('This is my name.')->charAt(6);

// 's'

classBasename

classBasename 方法会返回给定类的类名,并移除其命名空间:

php
use Illuminate\Support\Str;

$class = Str::of('Foo\Bar\Baz')->classBasename();

// 'Baz'

chopStart

chopStart 方法仅在给定值出现在字符串开头时,移除它的第一次出现:

php
use Illuminate\Support\Str;

$url = Str::of('https://laravel.com')->chopStart('https://');

// 'laravel.com'

你也可以传入一个数组。如果字符串以数组中的任意一个值开头,则会从字符串中移除该值:

php
use Illuminate\Support\Str;

$url = Str::of('http://laravel.com')->chopStart(['https://', 'http://']);

// 'laravel.com'

chopEnd

chopEnd 方法仅在给定值出现在字符串末尾时,移除它的最后一次出现:

php
use Illuminate\Support\Str;

$url = Str::of('https://laravel.com')->chopEnd('.com');

// 'https://laravel'

你也可以传入一个数组。如果字符串以数组中的任意一个值结尾,则会从字符串中移除该值:

php
use Illuminate\Support\Str;

$url = Str::of('http://laravel.com')->chopEnd(['.com', '.io']);

// 'http://laravel'

contains

contains 方法会判断给定字符串是否包含指定值。默认情况下,此方法区分大小写:

php
use Illuminate\Support\Str;

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

// true

你也可以传入一个值数组,以判断给定字符串是否包含数组中的任意一个值:

php
use Illuminate\Support\Str;

$contains = Str::of('This is my name')->contains(['my', 'foo']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$contains = Str::of('This is my name')->contains('MY', ignoreCase: true);

// true

containsAll

containsAll 方法会判断给定字符串是否包含给定数组中的所有值:

php
use Illuminate\Support\Str;

$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$containsAll = Str::of('This is my name')->containsAll(['MY', 'NAME'], ignoreCase: true);

// true

decrypt

decrypt 方法会对加密字符串进行解密

php
use Illuminate\Support\Str;

$decrypted = $encrypted->decrypt();

// 'secret'

decrypt 的逆操作请参见 encrypt 方法。

deduplicate

deduplicate 方法会将给定字符串中连续重复的某个字符替换为单个字符。默认情况下,该方法会去重空格:

php
use Illuminate\Support\Str;

$result = Str::of('The   Laravel   Framework')->deduplicate();

// The Laravel Framework

你可以通过将不同的字符作为第二个参数传入,指定要去重的字符:

php
use Illuminate\Support\Str;

$result = Str::of('The---Laravel---Framework')->deduplicate('-');

// The-Laravel-Framework

dirname

dirname 方法会返回给定字符串中的父目录部分:

php
use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname();

// '/foo/bar'

如有需要,你可以指定要从字符串中裁剪掉多少层目录:

php
use Illuminate\Support\Str;

$string = Str::of('/foo/bar/baz')->dirname(2);

// '/foo'

doesntContain()

doesntContain 方法会判断给定字符串是否不包含指定值。该方法是 contains 方法的逆操作。默认情况下,此方法区分大小写:

php
use Illuminate\Support\Str;

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

// true

你也可以传入一个值数组,以判断给定字符串是否不包含数组中的任何值:

php
use Illuminate\Support\Str;

$doesntContain = Str::of('This is name')->doesntContain(['my', 'framework']);

// true

你可以将 ignoreCase 参数设置为 true 来关闭大小写敏感:

php
use Illuminate\Support\Str;

$doesntContain = Str::of('This is my name')->doesntContain('MY', ignoreCase: true);

// false

doesntEndWith

doesntEndWith 方法会判断给定字符串是否不以指定值结尾:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->doesntEndWith('dog');

// true

你也可以传入一个值数组,以判断给定字符串是否不以数组中的任何一个值结尾:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->doesntEndWith(['this', 'foo']);

// true

$result = Str::of('This is my name')->doesntEndWith(['name', 'foo']);

// false

doesntStartWith

doesntStartWith 方法会判断给定字符串是否不以指定值开头:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->doesntStartWith('That');

// true

你也可以传入一个值数组,以判断给定字符串是否不以数组中的任何一个值开头:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->doesntStartWith(['What', 'That', 'There']);

// true

encrypt

encrypt 方法会对字符串进行加密

php
use Illuminate\Support\Str;

$encrypted = Str::of('secret')->encrypt();

encrypt 的逆操作请参见 decrypt 方法。

endsWith

endsWith 方法会判断给定字符串是否以指定值结尾:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->endsWith('name');

// true

你也可以传入一个值数组,以判断给定字符串是否以数组中的任意一个值结尾:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->endsWith(['name', 'foo']);

// true

$result = Str::of('This is my name')->endsWith(['this', 'foo']);

// false

exactly

exactly 方法会判断给定字符串是否与另一个字符串完全匹配:

php
use Illuminate\Support\Str;

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

// true

excerpt

excerpt 方法会从字符串中提取包含某个短语首次匹配位置的摘要:

php
use Illuminate\Support\Str;

$excerpt = Str::of('This is my name')->excerpt('my', [
    'radius' => 3
]);

// '...is my na...'

radius 选项默认值为 100,用于定义截断字符串两侧应显示的字符数。

此外,你可以使用 omission 选项来修改追加到截断字符串前后的字符串:

php
use Illuminate\Support\Str;

$excerpt = Str::of('This is my name')->excerpt('name', [
    'radius' => 3,
    'omission' => '(...) '
]);

// '(...) my name'

explode

explode 方法会按给定分隔符拆分字符串,并返回一个包含各个拆分片段的 collection:

php
use Illuminate\Support\Str;

$collection = Str::of('foo bar baz')->explode(' ');

// collect(['foo', 'bar', 'baz'])

finish

finish 方法会在字符串尚未以给定值结尾时,为其追加一个该值:

php
use Illuminate\Support\Str;

$adjusted = Str::of('this/string')->finish('/');

// this/string/

$adjusted = Str::of('this/string/')->finish('/');

// this/string/

fromBase64

fromBase64 方法会解码给定的 Base64 字符串:

php
use Illuminate\Support\Str;

$decoded = Str::of('TGFyYXZlbA==')->fromBase64();

// Laravel

hash

hash 方法会使用给定的算法对字符串进行哈希处理:

php
use Illuminate\Support\Str;

$hashed = Str::of('secret')->hash(algorithm: 'sha256');

// '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'

headline

headline 方法会将按大小写、连字符或下划线分隔的字符串转换为空格分隔,并将每个单词首字母大写的字符串:

php
use Illuminate\Support\Str;

$headline = Str::of('taylor_otwell')->headline();

// Taylor Otwell

$headline = Str::of('EmailNotificationSent')->headline();

// Email Notification Sent

initials

initials 方法会返回给定字符串的首字母缩写,并可选择将其转为大写:

php
use Illuminate\Support\Str;

$initials = Str::of('taylor otwell')->initials();

// to

$initials = Str::of('taylor otwell')->initials(capitalize: true);

// TO

inlineMarkdown

inlineMarkdown 方法会使用 CommonMark 将 GitHub 风格 Markdown 转换为内联 HTML。不过,与 markdown 方法不同的是,它不会将生成的 HTML 包裹在块级元素中:

php
use Illuminate\Support\Str;

$html = Str::of('**Laravel**')->inlineMarkdown();

// <strong>Laravel</strong>

Markdown 安全性

默认情况下,Markdown 支持原始 HTML,这在处理原始用户输入时会带来跨站脚本攻击(XSS)漏洞。根据 CommonMark 安全文档,你可以使用 html_input 选项对原始 HTML 进行转义或剥离,并通过 allow_unsafe_links 选项指定是否允许不安全链接。如果你需要允许部分原始 HTML,应当将编译后的 Markdown 再交给 HTML Purifier 处理:

php
use Illuminate\Support\Str;

Str::of('Inject: <script>alert("Hello XSS!");</script>')->inlineMarkdown([
    'html_input' => 'strip',
    'allow_unsafe_links' => false,
]);

// Inject: alert(&quot;Hello XSS!&quot;);

is

is 方法会判断给定字符串是否匹配指定模式。星号可用作通配符

php
use Illuminate\Support\Str;

$matches = Str::of('foobar')->is('foo*');

// true

$matches = Str::of('foobar')->is('baz*');

// false

isAscii

isAscii 方法会判断给定字符串是否为 ASCII 字符串:

php
use Illuminate\Support\Str;

$result = Str::of('Taylor')->isAscii();

// true

$result = Str::of('ü')->isAscii();

// false

isEmpty

isEmpty 方法会判断给定字符串是否为空:

php
use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isEmpty();

// true

$result = Str::of('Laravel')->trim()->isEmpty();

// false

isNotEmpty

isNotEmpty 方法会判断给定字符串是否不为空:

php
use Illuminate\Support\Str;

$result = Str::of('  ')->trim()->isNotEmpty();

// false

$result = Str::of('Laravel')->trim()->isNotEmpty();

// true

isJson

isJson 方法会判断给定字符串是否为有效的 JSON:

php
use Illuminate\Support\Str;

$result = Str::of('[1,2,3]')->isJson();

// true

$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();

// true

$result = Str::of('{first: "John", last: "Doe"}')->isJson();

// false

isUlid

isUlid 方法会判断给定字符串是否为 ULID:

php
use Illuminate\Support\Str;

$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();

// true

$result = Str::of('Taylor')->isUlid();

// false

isUrl

isUrl 方法会判断给定字符串是否为 URL:

php
use Illuminate\Support\Str;

$result = Str::of('http://example.com')->isUrl();

// true

$result = Str::of('Taylor')->isUrl();

// false

isUrl 方法默认会将多种协议视为有效。不过,你也可以将允许的协议传给 isUrl 方法,以明确指定哪些协议应被视为有效:

php
$result = Str::of('http://example.com')->isUrl(['http', 'https']);

isUuid

isUuid 方法会判断给定字符串是否为 UUID:

php
use Illuminate\Support\Str;

$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();

// true

$result = Str::of('Taylor')->isUuid();

// false

你还可以校验给定 UUID 是否符合指定版本(1、3、4、5、6、7 或 8)的 UUID 规范:

php
use Illuminate\Support\Str;

$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 4);

// true

$isUuid = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->isUuid(version: 1);

// false

kebab

kebab 方法会将给定字符串转换为 kebab-case

php
use Illuminate\Support\Str;

$converted = Str::of('fooBar')->kebab();

// foo-bar

lcfirst

lcfirst 方法会返回将首字符转为小写后的字符串:

php
use Illuminate\Support\Str;

$string = Str::of('Foo Bar')->lcfirst();

// foo Bar

length

length 方法会返回给定字符串的长度:

php
use Illuminate\Support\Str;

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

// 7

limit

limit 方法会将给定字符串截断为指定长度:

php
use Illuminate\Support\Str;

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);

// The quick brown fox...

你也可以传入第二个参数,以修改追加到截断字符串末尾的内容:

php
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');

// The quick brown fox (...)

如果你希望在截断字符串时保留完整单词,可以使用 preserveWords 参数。当该参数为 true 时,字符串会在最近的完整单词边界处被截断:

php
$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true);

// The quick...

lower

lower 方法会将给定字符串转换为小写:

php
use Illuminate\Support\Str;

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

// 'laravel'

markdown

markdown 方法会将 GitHub 风格 Markdown 转换为 HTML:

php
use Illuminate\Support\Str;

$html = Str::of('# Laravel')->markdown();

// <h1>Laravel</h1>

$html = Str::of('# Taylor <b>Otwell</b>')->markdown([
    'html_input' => 'strip',
]);

// <h1>Taylor Otwell</h1>

Markdown 安全性

默认情况下,Markdown 支持原始 HTML,这在处理原始用户输入时会带来跨站脚本攻击(XSS)漏洞。根据 CommonMark 安全文档,你可以使用 html_input 选项对原始 HTML 进行转义或剥离,并通过 allow_unsafe_links 选项指定是否允许不安全链接。如果你需要允许部分原始 HTML,应当将编译后的 Markdown 再交给 HTML Purifier 处理:

php
use Illuminate\Support\Str;

Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([
    'html_input' => 'strip',
    'allow_unsafe_links' => false,
]);

// <p>Inject: alert(&quot;Hello XSS!&quot;);</p>

mask

mask 方法会使用重复字符遮罩字符串中的一部分,可用于模糊处理电子邮件地址、电话号码等字符串片段:

php
use Illuminate\Support\Str;

$string = Str::of('taylor@example.com')->mask('*', 3);

// tay***************

如果需要,你可以将负数作为 mask 方法的第三个或第四个参数传入,这会让该方法从距离字符串末尾指定距离的位置开始进行遮罩:

php
$string = Str::of('taylor@example.com')->mask('*', -15, 3);

// tay***@example.com

$string = Str::of('taylor@example.com')->mask('*', 4, -4);

// tayl**********.com

match

match 方法会返回字符串中匹配给定正则表达式模式的部分:

php
use Illuminate\Support\Str;

$result = Str::of('foo bar')->match('/bar/');

// 'bar'

$result = Str::of('foo bar')->match('/foo (.*)/');

// 'bar'

matchAll

matchAll 方法会返回一个 collection,其中包含字符串中匹配给定正则表达式模式的所有部分:

php
use Illuminate\Support\Str;

$result = Str::of('bar foo bar')->matchAll('/bar/');

// collect(['bar', 'bar'])

如果你在表达式中指定了匹配组,Laravel 将返回一个 collection,其中包含第一个匹配组的匹配结果:

php
use Illuminate\Support\Str;

$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');

// collect(['un', 'ly']);

如果没有找到匹配项,将返回一个空的 collection。

isMatch

如果字符串匹配给定正则表达式,isMatch 方法将返回 true

php
use Illuminate\Support\Str;

$result = Str::of('foo bar')->isMatch('/foo (.*)/');

// true

$result = Str::of('laravel')->isMatch('/foo (.*)/');

// false

newLine

newLine 方法会向字符串追加一个“行结束”字符:

php
use Illuminate\Support\Str;

$padded = Str::of('Laravel')->newLine()->append('Framework');

// 'Laravel
//  Framework'

padBoth

padBoth 方法封装了 PHP 的 str_pad 函数,会在字符串两侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::of('James')->padBoth(10, '_');

// '__James___'

$padded = Str::of('James')->padBoth(10);

// '  James   '

padLeft

padLeft 方法封装了 PHP 的 str_pad 函数,会在字符串左侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::of('James')->padLeft(10, '-=');

// '-=-=-James'

$padded = Str::of('James')->padLeft(10);

// '     James'

padRight

padRight 方法封装了 PHP 的 str_pad 函数,会在字符串右侧填充另一个字符串,直到最终字符串达到指定长度:

php
use Illuminate\Support\Str;

$padded = Str::of('James')->padRight(10, '-');

// 'James-----'

$padded = Str::of('James')->padRight(10);

// 'James     '

pipe

pipe 方法允许你将字符串当前值传给指定 callable,从而对字符串进行转换:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');

// 'Checksum: a5c95b86291ea299fcbe64458ed12702'

$closure = Str::of('foo')->pipe(function (Stringable $str) {
    return 'bar';
});

// 'bar'

plural

plural 方法会将单数单词字符串转换为复数形式。此函数支持 Laravel 复数化器支持的所有语言

php
use Illuminate\Support\Str;

$plural = Str::of('car')->plural();

// cars

$plural = Str::of('child')->plural();

// children

你可以向该函数传入一个整数参数,以获取字符串的单数或复数形式:

php
use Illuminate\Support\Str;

$plural = Str::of('child')->plural(2);

// children

$plural = Str::of('child')->plural(1);

// child

你可以提供 prependCount 参数,以便在复数化后的字符串前加上格式化后的 $count

php
use Illuminate\Support\Str;

$label = Str::of('car')->plural(1000, prependCount: true);

// 1,000 cars

position

position 方法会返回子字符串在字符串中首次出现的位置。如果该子字符串不存在于字符串中,则返回 false

php
use Illuminate\Support\Str;

$position = Str::of('Hello, World!')->position('Hello');

// 0

$position = Str::of('Hello, World!')->position('W');

// 7

prepend

prepend 方法会将给定值前置到字符串前面:

php
use Illuminate\Support\Str;

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

// Laravel Framework

remove

remove 方法会从字符串中移除给定值或值数组:

php
use Illuminate\Support\Str;

$string = Str::of('Arkansas is quite beautiful!')->remove('quite ');

// Arkansas is beautiful!

你也可以将 false 作为第二个参数传入,以在移除字符串时忽略大小写。

repeat

repeat 方法会重复给定字符串:

php
use Illuminate\Support\Str;

$repeated = Str::of('a')->repeat(5);

// aaaaa

replace

replace 方法会替换字符串中的指定内容:

php
use Illuminate\Support\Str;

$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');

// Laravel 7.x

replace 方法还接受一个 caseSensitive 参数。默认情况下,replace 方法区分大小写:

php
$replaced = Str::of('macOS 13.x')->replace(
    'macOS', 'iOS', caseSensitive: false
);

replaceArray

replaceArray 方法会使用数组按顺序替换字符串中的给定值:

php
use Illuminate\Support\Str;

$string = 'The event will take place between ? and ?';

$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);

// The event will take place between 8:30 and 9:00

replaceFirst

replaceFirst 方法会替换字符串中给定值的第一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');

// a quick brown fox jumps over the lazy dog

replaceLast

replaceLast 方法会替换字符串中给定值的最后一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');

// the quick brown fox jumps over a lazy dog

replaceMatches

replaceMatches 方法会将字符串中所有匹配某个模式的部分替换为给定的替换字符串:

php
use Illuminate\Support\Str;

$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')

// '15015551000'

replaceMatches 方法还接受一个 closure,它会针对字符串中每个匹配给定模式的部分被调用,让你可以在 closure 中执行替换逻辑并返回替换后的值:

php
use Illuminate\Support\Str;

$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
    return '['.$matches[0].']';
});

// '[1][2][3]'

replaceStart

replaceStart 方法仅在给定值出现在字符串开头时,替换它的第一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::of('Hello World')->replaceStart('Hello', 'Laravel');

// Laravel World

$replaced = Str::of('Hello World')->replaceStart('World', 'Laravel');

// Hello World

replaceEnd

replaceEnd 方法仅在给定值出现在字符串末尾时,替换它的最后一次出现:

php
use Illuminate\Support\Str;

$replaced = Str::of('Hello World')->replaceEnd('World', 'Laravel');

// Hello Laravel

$replaced = Str::of('Hello World')->replaceEnd('Hello', 'Laravel');

// Hello World

scan

scan 方法会按照 sscanf PHP 函数支持的格式,从字符串中解析输入到一个 collection 中:

php
use Illuminate\Support\Str;

$collection = Str::of('filename.jpg')->scan('%[^.].%s');

// collect(['filename', 'jpg'])

singular

singular 方法会将字符串转换为单数形式。此函数支持 Laravel 复数化器支持的所有语言

php
use Illuminate\Support\Str;

$singular = Str::of('cars')->singular();

// car

$singular = Str::of('children')->singular();

// child

slug

slug 方法会根据给定字符串生成对 URL 友好的 “slug”:

php
use Illuminate\Support\Str;

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

// laravel-framework

snake

snake 方法会将给定字符串转换为 snake_case

php
use Illuminate\Support\Str;

$converted = Str::of('fooBar')->snake();

// foo_bar

split

split 方法会使用正则表达式将字符串拆分为一个 collection:

php
use Illuminate\Support\Str;

$segments = Str::of('one, two, three')->split('/[\s,]+/');

// collect(["one", "two", "three"])

squish

squish 方法会移除字符串中的所有多余空白,包括单词之间多余的空白:

php
use Illuminate\Support\Str;

$string = Str::of('    laravel    framework    ')->squish();

// laravel framework

start

start 方法会在字符串尚未以给定值开头时,为其添加一个该值:

php
use Illuminate\Support\Str;

$adjusted = Str::of('this/string')->start('/');

// /this/string

$adjusted = Str::of('/this/string')->start('/');

// /this/string

startsWith

startsWith 方法会判断给定字符串是否以指定值开头:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->startsWith('This');

// true

你也可以传入一个值数组,以判断给定字符串是否以数组中的任意一个值开头:

php
use Illuminate\Support\Str;

$result = Str::of('This is my name')->startsWith(['This', 'That']);

// true

stripTags

stripTags 方法会移除字符串中的所有 HTML 和 PHP 标签:

php
use Illuminate\Support\Str;

$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags();

// Taylor Otwell

$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></a>')->stripTags('<b>');

// Taylor <b>Otwell</b>

studly

studly 方法会将给定字符串转换为 StudlyCase

php
use Illuminate\Support\Str;

$converted = Str::of('foo_bar')->studly();

// FooBar

substr

substr 方法会返回由起始位置和长度参数指定的字符串片段:

php
use Illuminate\Support\Str;

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

// Framework

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

// Frame

substrReplace

substrReplace 方法会替换字符串某一部分中的文本,起始位置由第二个参数指定,替换字符数由第三个参数指定。如果将第三个参数设为 0,则会在指定位置插入字符串,而不会替换字符串中现有的任何字符:

php
use Illuminate\Support\Str;

$string = Str::of('1300')->substrReplace(':', 2);

// 13:

$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);

// The Laravel Framework

swap

swap 方法会使用 PHP 的 strtr 函数替换字符串中的多个值:

php
use Illuminate\Support\Str;

$string = Str::of('Tacos are great!')
    ->swap([
        'Tacos' => 'Burritos',
        'great' => 'fantastic',
    ]);

// Burritos are fantastic!

take

take 方法会从字符串开头返回指定数量的字符:

php
use Illuminate\Support\Str;

$taken = Str::of('Build something amazing!')->take(5);

// Build

tap

tap 方法会将字符串传给给定的 closure,让你可以在不影响字符串本身的情况下检查并操作它。无论 closure 返回什么,tap 方法都会返回原始字符串:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('Laravel')
    ->append(' Framework')
    ->tap(function (Stringable $string) {
        dump('String after append: '.$string);
    })
    ->upper();

// LARAVEL FRAMEWORK

test

test 方法会判断字符串是否匹配给定的正则表达式模式:

php
use Illuminate\Support\Str;

$result = Str::of('Laravel Framework')->test('/Laravel/');

// true

title

title 方法会将给定字符串转换为 Title Case

php
use Illuminate\Support\Str;

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

// A Nice Title Uses The Correct Case

toBase64

toBase64 方法会将给定字符串转换为 Base64:

php
use Illuminate\Support\Str;

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

// TGFyYXZlbA==

toHtmlString

toHtmlString 方法会将给定字符串转换为 Illuminate\Support\HtmlString 实例,在 Blade 模板中渲染时不会被转义:

php
use Illuminate\Support\Str;

$htmlString = Str::of('Nuno Maduro')->toHtmlString();

toUri

toUri 方法会将给定字符串转换为 Illuminate\Support\Uri 实例:

php
use Illuminate\Support\Str;

$uri = Str::of('https://example.com')->toUri();

transliterate

transliterate 方法会尝试将给定字符串转换为最接近的 ASCII 表示:

php
use Illuminate\Support\Str;

$email = Str::of('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ')->transliterate()

// 'test@laravel.com'

trim

trim 方法会修剪给定字符串。与 PHP 原生的 trim 函数不同,Laravel 的 trim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

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

// 'Laravel'

$string = Str::of('/Laravel/')->trim('/');

// 'Laravel'

ltrim

ltrim 方法会修剪字符串左侧。与 PHP 原生的 ltrim 函数不同,Laravel 的 ltrim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

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

// 'Laravel  '

$string = Str::of('/Laravel/')->ltrim('/');

// 'Laravel/'

rtrim

rtrim 方法会修剪给定字符串右侧。与 PHP 原生的 rtrim 函数不同,Laravel 的 rtrim 方法还会移除 Unicode 空白字符:

php
use Illuminate\Support\Str;

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

// '  Laravel'

$string = Str::of('/Laravel/')->rtrim('/');

// '/Laravel'

ucfirst

ucfirst 方法会返回首字符大写后的字符串:

php
use Illuminate\Support\Str;

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

// Foo bar

ucsplit

ucsplit 方法会按大写字符将给定字符串拆分为一个 collection:

php
use Illuminate\Support\Str;

$string = Str::of('Foo Bar')->ucsplit();

// collect(['Foo ', 'Bar'])

ucwords

ucwords 方法会将给定字符串中每个单词的首字符转换为大写:

php
use Illuminate\Support\Str;

$string = Str::of('laravel framework')->ucwords();

// Laravel Framework

unwrap

unwrap 方法会从给定字符串的开头和结尾移除指定字符串:

php
use Illuminate\Support\Str;

Str::of('-Laravel-')->unwrap('-');

// Laravel

Str::of('{framework: "Laravel"}')->unwrap('{', '}');

// framework: "Laravel"

upper

upper 方法会将给定字符串转换为大写:

php
use Illuminate\Support\Str;

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

// LARAVEL

when

when 方法会在给定条件为 true 时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('Taylor')
    ->when(true, function (Stringable $string) {
        return $string->append(' Otwell');
    });

// 'Taylor Otwell'

如有需要,你可以将另一个 closure 作为第三个参数传给 when 方法。当条件参数的结果为 false 时,这个 closure 会执行。

whenContains

whenContains 方法会在字符串包含给定值时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('tony stark')
    ->whenContains('tony', function (Stringable $string) {
        return $string->title();
    });

// 'Tony Stark'

如有需要,你可以将另一个 closure 作为第三个参数传入。当字符串不包含给定值时,这个 closure 会被调用。

你也可以传入一个值数组,以判断给定字符串是否包含数组中的任意一个值:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('tony stark')
    ->whenContains(['tony', 'hulk'], function (Stringable $string) {
        return $string->title();
    });

// Tony Stark

whenContainsAll

whenContainsAll 方法会在字符串包含所有给定子字符串时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('tony stark')
    ->whenContainsAll(['tony', 'stark'], function (Stringable $string) {
        return $string->title();
    });

// 'Tony Stark'

如有需要,你可以将另一个 closure 作为第三个参数传入。当条件参数的结果为 false 时,这个 closure 会被调用。

whenDoesntEndWith

whenDoesntEndWith 方法会在字符串不以给定子字符串结尾时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('disney world')->whenDoesntEndWith('land', function (Stringable $string) {
    return $string->title();
});

// 'Disney World'

whenDoesntStartWith

whenDoesntStartWith 方法会在字符串不以给定子字符串开头时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('disney world')->whenDoesntStartWith('sea', function (Stringable $string) {
    return $string->title();
});

// 'Disney World'

whenEmpty

whenEmpty 方法会在字符串为空时调用指定 closure。如果该 closure 返回一个值,whenEmpty 方法也会返回该值;如果 closure 没有返回值,则返回 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('  ')->trim()->whenEmpty(function (Stringable $string) {
    return $string->prepend('Laravel');
});

// 'Laravel'

whenNotEmpty

whenNotEmpty 方法会在字符串不为空时调用指定 closure。如果该 closure 返回一个值,whenNotEmpty 方法也会返回该值;如果 closure 没有返回值,则返回 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('Framework')->whenNotEmpty(function (Stringable $string) {
    return $string->prepend('Laravel ');
});

// 'Laravel Framework'

whenStartsWith

whenStartsWith 方法会在字符串以给定子字符串开头时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('disney world')->whenStartsWith('disney', function (Stringable $string) {
    return $string->title();
});

// 'Disney World'

whenEndsWith

whenEndsWith 方法会在字符串以给定子字符串结尾时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('disney world')->whenEndsWith('world', function (Stringable $string) {
    return $string->title();
});

// 'Disney World'

whenExactly

whenExactly 方法会在字符串与给定字符串完全匹配时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('laravel')->whenExactly('laravel', function (Stringable $string) {
    return $string->title();
});

// 'Laravel'

whenNotExactly

whenNotExactly 方法会在字符串与给定字符串不完全匹配时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('framework')->whenNotExactly('laravel', function (Stringable $string) {
    return $string->title();
});

// 'Framework'

whenIs

whenIs 方法会在字符串匹配给定模式时调用指定 closure。星号可用作通配符。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('foo/bar')->whenIs('foo/*', function (Stringable $string) {
    return $string->append('/baz');
});

// 'foo/bar/baz'

whenIsAscii

whenIsAscii 方法会在字符串为 7 位 ASCII 时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('laravel')->whenIsAscii(function (Stringable $string) {
    return $string->title();
});

// 'Laravel'

whenIsUlid

whenIsUlid 方法会在字符串是有效 ULID 时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;

$string = Str::of('01gd6r360bp37zj17nxb55yv40')->whenIsUlid(function (Stringable $string) {
    return $string->substr(0, 8);
});

// '01gd6r36'

whenIsUuid

whenIsUuid 方法会在字符串是有效 UUID 时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('a0a2a2d2-0b87-4a18-83f2-2529882be2de')->whenIsUuid(function (Stringable $string) {
    return $string->substr(0, 8);
});

// 'a0a2a2d2'

whenTest

whenTest 方法会在字符串匹配给定正则表达式时调用指定 closure。该 closure 会接收 fluent string 实例:

php
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$string = Str::of('laravel framework')->whenTest('/laravel/', function (Stringable $string) {
    return $string->title();
});

// 'Laravel Framework'

wordCount

wordCount 方法会返回字符串包含的单词数量:

php
use Illuminate\Support\Str;

Str::of('Hello, world!')->wordCount(); // 2

words

words 方法会限制字符串中的单词数量。如有需要,你可以指定一个附加字符串,追加到截断字符串末尾:

php
use Illuminate\Support\Str;

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

// Perfectly balanced, as >>>

wrap

wrap 方法会使用另一个字符串或一对字符串包裹给定字符串:

php
use Illuminate\Support\Str;

Str::of('Laravel')->wrap('"');

// "Laravel"

Str::is('is')->wrap(before: 'This ', after: ' Laravel!');

// This is Laravel!