介绍
Laravel 包含多种用于操作字符串值的函数。许多这些函数由框架本身使用;然而,如果您觉得方便,也可以在自己的应用程序中使用它们。
可用方法
字符串
__ class_basename e preg_replace_array Str::after Str::afterLast Str::apa Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::charAt Str::chopStart Str::chopEnd Str::contains Str::containsAll Str::deduplicate Str::endsWith Str::excerpt Str::finish Str::headline Str::inlineMarkdown Str::is Str::isAscii Str::isJson Str::isUlid Str::isUrl Str::isUuid Str::kebab Str::lcfirst Str::length Str::limit Str::lower Str::markdown Str::mask Str::orderedUuid Str::padBoth Str::padLeft Str::padRight Str::password Str::plural Str::pluralStudly Str::position Str::random Str::remove Str::repeat Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast Str::replaceMatches Str::replaceStart Str::replaceEnd Str::reverse Str::singular Str::slug Str::snake Str::squish Str::start Str::startsWith Str::studly Str::substr Str::substrCount Str::substrReplace Str::swap Str::take Str::title Str::toBase64 Str::toHtmlString Str::transliterate Str::trim Str::ltrim Str::rtrim Str::ucfirst Str::ucsplit Str::upper Str::ulid Str::unwrap Str::uuid Str::wordCount Str::wordWrap Str::words Str::wrap str trans trans_choice
流畅字符串
after afterLast apa append ascii basename before beforeLast between betweenFirst camel charAt classBasename chopStart chopEnd contains containsAll deduplicate dirname endsWith exactly excerpt explode finish headline inlineMarkdown is isAscii isEmpty isNotEmpty isJson isUlid isUrl isUuid kebab lcfirst length limit lower markdown mask match matchAll isMatch newLine padBoth padLeft padRight pipe plural position prepend remove repeat replace replaceArray replaceFirst replaceLast replaceMatches replaceStart replaceEnd scan singular slug snake split squish start startsWith stripTags studly substr substrReplace swap take tap test title toBase64 transliterate trim ltrim rtrim ucfirst ucsplit unwrap upper when whenContains whenContainsAll whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words
字符串
__()
{.collection-method}
__
函数使用您的语言文件翻译给定的翻译字符串或翻译键:
echo __('欢迎来到我们的应用程序');
echo __('messages.welcome');
如果指定的翻译字符串或键不存在,__
函数将返回给定的值。因此,使用上面的示例,如果 messages.welcome
这个翻译键不存在,__
函数将返回 messages.welcome
。
class_basename()
{.collection-method}
class_basename
函数返回给定类的类名,去除类的命名空间:
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
{.collection-method}
e
函数默认以 double_encode
选项设置为 true
运行 PHP 的 htmlspecialchars
函数:
echo e('<html>foo</html>');
// <html>foo</html>
preg_replace_array()
{.collection-method}
preg_replace_array
函数使用数组按顺序替换字符串中的给定模式:
$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()
{.collection-method}
Str::after
方法返回字符串中给定值之后的所有内容。如果字符串中不存在该值,则返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'
Str::afterLast()
{.collection-method}
Str::afterLast
方法返回字符串中给定值最后一次出现之后的所有内容。如果字符串中不存在该值,则返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
// 'Controller'
Str::apa()
{.collection-method}
Str::apa
方法根据APA 指南 (opens in a new tab)将给定的字符串转换为标题大小写:
use Illuminate\Support\Str;
$title = Str::apa('Creating A Project');
// 'Creating a Project'
Str::ascii()
{.collection-method}
Str::ascii
方法将尝试将字符串音译为 ASCII 值:
use Illuminate\Support\Str;
$slice = Str::ascii('û');
// 'u'
Str::before()
{.collection-method}
Str::before
方法返回字符串中给定值之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
// 'This is '
Str::beforeLast()
{.collection-method}
Str::beforeLast
方法返回字符串中给定值最后一次出现之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::beforeLast('This is my name', 'is');
// 'This '
Str::between()
{.collection-method}
Str::between
方法返回字符串中两个值之间的部分:
use Illuminate\Support\Str;
$slice = Str::between('This is my name', 'This', 'name');
// ' is my '
Str::betweenFirst()
{.collection-method}
Str::betweenFirst
方法返回字符串中两个值之间的最小可能部分:
use Illuminate\Support\Str;
$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
// 'a'
Str::camel()
{.collection-method}
Str::camel
方法将给定的字符串转换为 camelCase
:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// 'fooBar'
Str::charAt()
{.collection-method}
Str::charAt
方法返回指定索引处的字符。如果索引超出范围,则返回 false
:
use Illuminate\Support\Str;
$character = Str::charAt('This is my name.', 6);
// 's'
Str::chopStart()
{.collection-method}
Str::chopStart
方法仅在给定值出现在字符串开头时删除其首次出现:
use Illuminate\Support\Str;
$url = Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'
您也可以将数组作为第二个参数传递。如果字符串以数组中的任何值开头,则该值将从字符串中删除:
use Illuminate\Support\Str;
$url = Str::chopStart('http://laravel.com', ['https://', 'http://']);
// 'laravel.com'
Str::chopEnd()
{.collection-method}
Str::chopEnd
方法仅在给定值出现在字符串末尾时删除其最后一次出现:
use Illuminate\Support\Str;
$url = Str::chopEnd('app/Models/Photograph.php', '.php');
// 'app/Models/Photograph'
您也可以将数组作为第二个参数传递。如果字符串以数组中的任何值结尾,则该值将从字符串中删除:
use Illuminate\Support\Str;
$url = Str::chopEnd('laravel.com/index.php', ['/index.html', '/index.php']);
// 'laravel.com'
Str::contains()
{.collection-method}
Str::contains
方法确定给定字符串是否包含给定值。默认情况下,此方法区分大小写:
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', 'my');
// true
您也可以传递一个值数组来确定给定字符串是否包含数组中的任何值:
use Illuminate\Support\Str;
$contains = Str::contains('This is my name', ['my', 'foo']);
// true
您可以通过将 ignoreCase
参数设置为 true
来禁用区分大小写:
use Illuminate\Support\Str
Str::remove()
{.collection-method}
Str::remove
方法从字符串中移除给定的值或值的数组:
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()
{.collection-method}
Str::repeat
方法重复给定的字符串:
use Illuminate\Support\Str;
$string = 'a';
$repeat = Str::repeat($string, 5);
// aaaaa
Str::replace()
{.collection-method}
Str::replace
方法在字符串内替换给定的字符串:
use Illuminate\Support\Str;
$string = 'Laravel 10.x';
$replaced = Str::replace('10.x', '11.x', $string);
// Laravel 11.x
replace
方法也接受一个 caseSensitive
参数。默认情况下,replace
方法是区分大小写的:
Str::replace('Framework', 'Laravel', caseSensitive: false);
Str::replaceArray()
{.collection-method}
Str::replaceArray
方法使用数组按顺序替换字符串中的给定值:
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()
{.collection-method}
Str::replaceFirst
方法替换字符串中给定值的首次出现:
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()
{.collection-method}
Str::replaceLast
方法替换字符串中给定值的最后一次出现:
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()
{.collection-method}
Str::replaceMatches
方法使用给定的替换字符串替换字符串中与模式匹配的所有部分:
use Illuminate\Support\Str;
$replaced = Str::replaceMatches(
pattern: '/[^A-Za-z0-9]++/',
replace: '',
subject: '(+1) 501-555-1000'
)
// '15015551000'
replaceMatches
方法也接受一个闭包,该闭包将与字符串中与给定模式匹配的每个部分一起调用,允许您在闭包内执行替换逻辑并返回替换后的值:
use Illuminate\Support\Str;
$replaced = Str::replaceMatches('/\d/', function (array $matches) {
return '['.$matches[0].']';
}, '123');
// '[1][2][3]'
Str::replaceStart()
{.collection-method}
Str::replaceStart
方法仅在给定值出现在字符串开头时替换该值的首次出现:
use Illuminate\Support\Str;
$replaced = Str::replaceStart('Hello', 'Laravel', 'Hello World');
// Laravel World
$replaced = Str::replaceStart('World', 'Laravel', 'Hello World');
// Hello World
Str::replaceEnd()
{.collection-method}
Str::replaceEnd
方法仅在给定值出现在字符串末尾时替换该值的最后一次出现:
use Illuminate\Support\Str;
$replaced = Str::replaceEnd('World', 'Laravel', 'Hello World');
// Hello Laravel
$replaced = Str::replaceEnd('Hello', 'Laravel', 'Hello World');
// Hello World
Str::reverse()
{.collection-method}
Str::reverse
方法反转给定的字符串:
use Illuminate\Support\Str;
$reversed = Str::reverse('Hello World');
// dlroW olleH
Str::singular()
{.collection-method}
Str::singular
方法将字符串转换为其单数形式。此函数支持 Laravel 的复数器所支持的任何语言:
use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// child
Str::slug()
{.collection-method}
Str::slug
方法从给定的字符串生成一个对 URL 友好的“slug”:
use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');
// laravel-5-framework
Str::snake()
{.collection-method}
Str::snake
方法将给定的字符串转换为 snake_case
:
use Illuminate\Support\Str;
$converted = Str::snake('fooBar');
// foo_bar
$converted = Str::snake('fooBar', '-');
// foo-bar
Str::squish()
{.collection-method}
Str::squish
方法从字符串中删除所有多余的空白,包括单词之间的多余空白:
use Illuminate\Support\Str;
$string = Str::squish(' laravel framework ');
// laravel framework
Str::start()
{.collection-method}
Str::start
方法如果字符串未以给定值开头,则向字符串添加该值的单个实例:
use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/string
Str::startsWith()
{.collection-method}
Str::startsWith
方法确定给定的字符串是否以给定的值开头:
use Illuminate\Support\Str;
$result = Str::startsWith('This is my name', 'This');
// true
如果传递了一个可能值的数组,startsWith
方法将在字符串以任何给定值开头时返回 true
:
$result = Str::startsWith('This is my name', ['This', 'That', 'There']);
// true
Str::studly()
{.collection-method}
Str::studly
方法将给定的字符串转换为 StudlyCase
:
use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBar
Str::substr()
{.collection-method}
Str::substr
方法返回由起始和长度参数指定的字符串部分:
use Illuminate\Support\Str;
$converted = Str::substr('The Laravel Framework', 4, 7);
// Laravel
Str::substrCount()
{.collection-method}
Str::substrCount
方法返回给定字符串中给定值的出现次数:
use Illuminate\Support\Str;
$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
// 2
Str::substrReplace()
{.collection-method}
Str::substrReplace
方法从第三个参数指定的位置开始,替换字符串的一部分中的文本,并替换由第四个参数指定的字符数。将 0
传递给方法的第四个参数将在指定位置插入字符串,而不会替换字符串中现有的任何字符:
use Illuminate\Support\Str;
$result = Str::substrReplace('1300', ':', 2);
// 13:
$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00
Str::swap()
{.collection-method}
Str::swap
方法使用 PHP 的 strtr
函数在给定的字符串中替换多个值:
use Illuminate\Support\Str;
$string = Str::swap([
'Tacos' => 'Burritos',
'great' => 'fantastic',
], 'Tacos are great!');
// Burritos are fantastic!
Str::take()
{.collection-method}
Str::take
方法从字符串的开头返回指定数量的字符:
use Illuminate\Support\Str;
$taken = Str::take('Build something amazing!', 5);
// Build
Str::title()
{.collection-method}
Str::title
方法将给定的字符串转换为 Title Case
:
use Illuminate\Support\Str;
$converted = Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct Case
Str::toBase64()
{.collection-method}
Str::toBase64
方法将给定的字符串转换为 Base64:
use Illuminate\Support\Str;
$base64 = Str::toBase64('Laravel');
// TGFyYXZlbA==
Str::toHtmlString()
{.collection-method}
Str::toHtmlString
方法将字符串实例转换为 Illuminate\Support\HtmlString
的实例,该实例可以在 Blade 模板中显示:
use Illuminate\Support\Str;
$htmlString = Str::of('Nuno Maduro')->toHtmlString();
Str::transliterate()
{.collection-method}
Str::transliterate
方法将尝试将给定的字符串转换为其最接近的 ASCII 表示:
use Illuminate\Support\Str;
$email = Str::transliterate('ⓣⓔⓢⓣ@ⓛⓐⓡⓐⓥⓔⓛ.ⓒⓞⓜ');
// 'test@laravel.com'
Str::trim()
{.collection-method}
Str::trim
方法从给定字符串的开头和结尾去除空白(或其他字符)。与 PHP 的原生 trim
函数不同,Str::trim
方法还会去除 Unicode 空白字符:
use Illuminate\Support\Str;
$string = Str::trim(' foo bar ');
// 'foo bar'
Str::ltrim()
{.collection-method}
Str::ltrim
方法从给定字符串的开头去除空白(或其他字符)。与 PHP 的原生 ltrim
函数不同,Str::ltrim
方法还会去除 Unicode 空白字符:
use Illuminate\Support\Str;
$string = Str::ltrim(' foo bar ');
// 'foo bar '
Str::rtrim()
{.collection-method}
Str::rtrim
方法从给定字符串的结尾去除空白(或其他字符)。与 PHP 的原生 rtrim
函数不同,Str::rtrim
方法还会去除 Unicode 空白字符:
use Illuminate\Support\Str;
$string = Str::rtrim(' foo bar ');
// ' foo bar'
Str::ucfirst()
{.collection-method}
Str::ucfirst
方法返回给定字符串,将第一个字符大写:
use Illuminate\Support\Str;
$string = Str::ucfirst('foo bar');
// Foo bar
Str::ucsplit()
{.collection-method}
Str::ucsplit
方法按大写字符将给定的字符串拆分为数组:
use Illuminate\Support\Str;
$segments = Str::ucsplit('FooBar');
// [0 => 'Foo', 1 => 'Bar']
Str::upper()
{.collection-method}
Str::upper
方法将给定的字符串转换为大写:
use Illuminate\Support\Str;
$string = Str::upper('laravel');
// LARAVEL
Str::ulid()
{.collection-method}
Str::ulid
方法生成一个 ULID,这是一个紧凑的、时间有序的唯一标识符:
use Illuminate\Support\Str;
return (string) Str::ulid();
// 01gd6r360bp37zj17nxb55yv40
如果您想要获取一个 Illuminate\Support\Carbon
日期实例,该实例表示给定 ULID 创建的日期和时间,您可以使用 Laravel 的 Carbon 集成提供的 createFromId
方法:
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
$date = Carbon::createFromId((string) Str::ulid());
在测试期间,可能需要“伪造” Str::ulid
方法返回的值。要实现此目的,您可以使用 createUlidsUsing
方法:
use Symfony\Component\Uid\Ulid;
Str::createUlidsUsing(function () {
return new Ulid('01HRDBNHHCKNW2AK4Z29SN82T9');
});
要指示 ulid
方法恢复正常生成 ULID,您可以调用 createUlidsNormally
方法:
Str::createUlidsNormally();
Str::unwrap()
{.collection-method}
Str::unwrap
方法从给定字符串的开头和结尾移除指定的字符串:
use Illuminate\Support\Str;
Str::unwrap('-Laravel-', '-');
// Laravel
Str::unwrap('{framework: "Laravel"}', '{', '}');
// framework: "Laravel"
Str::uuid()
{.collection-method}
Str::uuid
方法生成一个 UUID(版本 4):
use Illuminate\Support\Str;
return (string) Str::uuid();
在测试期间,可能需要“伪造” Str::uuid
方法返回的值。要实现此目的,您可以使用 createUuidsUsing
方法:
use Ramsey\Uuid\Uuid;
Str::createUuidsUsing(function () {
return Uuid::fromString('eadbfeac-5258-45c2-bab7-ccb9b5ef74f9');
});
要指示 uuid
方法恢复正常生成 UUID,您可以调用 createUuidsNormally
方法:
Str::createUuidsNormally();
Str::wordCount()
{.collection-method}
Str::wordCount
方法返回字符串包含的单词数量:
use Illuminate\Support\Str;
Str::wordCount('Hello, world!'); // 2
Str::wordWrap()
{.collection-method}
Str::wordWrap
方法将字符串按给定的字符数进行换行:
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()
{.collection-method}
Str::words
方法限制字符串中的单词数量。可以通过第三个参数向此方法传递一个附加字符串,以指定应将其附加到截断字符串的末尾:
use Illuminate\Support\Str;
return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// Perfectly balanced, as >>>
Str::wrap()
{.collection-method}
Str::wrap
方法用一个附加的字符串或一对字符串包裹给定的字符串:
use Illuminate\Support\Str;
Str::wrap('Laravel', '"');
// "Laravel"
Str::wrap('is', before: 'This ', after: ' Laravel!');
// This is Laravel!
str()
{.collection-method}
str
函数返回给定字符串的新 Illuminate\Support\Stringable
实例。此函数等同于 Str::of
方法:
$string = str('Taylor')->append(' Otwell');
// 'Taylor Otwell'
如果未向 str
函数提供参数,则该函数返回 Illuminate\Support\Str
的实例:
$snake = str()->snake('FooBar');
// 'foo_bar'
trans()
{.collection-method}
trans
函数使用您的 语言文件 翻译给定的翻译键:
echo trans('messages.welcome');
如果指定的翻译键不存在,trans
函数将返回给定的键。因此,使用上面的示例,如果翻译键不存在,trans
函数将返回 messages.welcome
。
trans_choice()
{.collection-method}
trans_choice
函数以屈折形式翻译给定的翻译键:
isUlid
{.collection-method}
isUlid
方法用于判断给定的字符串是否为 ULID:
use Illuminate\Support\Str;
$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();
// true
$result = Str::of('Taylor')->isUlid();
// false
isUrl
{.collection-method}
isUrl
方法用于判断给定的字符串是否为 URL:
use Illuminate\Support\Str;
$result = Str::of('http://example.com')->isUrl();
// true
$result = Str::of('Taylor')->isUrl();
// false
isUrl
方法认为多种协议是有效的。然而,您可以通过向 isUrl
方法提供协议来指定应被视为有效的协议:
$result = Str::of('http://example.com')->isUrl(['http', 'https']);
isUuid
{.collection-method}
isUuid
方法用于判断给定的字符串是否为 UUID:
use Illuminate\Support\Str;
$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
// true
$result = Str::of('Taylor')->isUuid();
// false
kebab
{.collection-method}
kebab
方法将给定的字符串转换为 kebab-case
:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->kebab();
// foo-bar
lcfirst
{.collection-method}
lcfirst
方法返回给定字符串,其首字符为小写:
use Illuminate\Support\Str;
$string = Str::of('Foo Bar')->lcfirst();
// foo Bar
length
{.collection-method}
length
方法返回给定字符串的长度:
use Illuminate\Support\Str;
$length = Str::of('Laravel')->length();
// 7
limit
{.collection-method}
limit
方法将给定的字符串截断到指定的长度:
use Illuminate\Support\Str;
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox...
您还可以传递第二个参数来更改将附加到截断字符串末尾的字符串:
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)
如果您希望在截断字符串时保留完整的单词,可以使用 preserveWords
参数。当此参数为 true
时,字符串将截断到最近的完整单词边界:
$truncated = Str::of('The quick brown fox')->limit(12, preserveWords: true);
// The quick...
lower
{.collection-method}
lower
方法将给定的字符串转换为小写:
use Illuminate\Support\Str;
$result = Str::of('LARAVEL')->lower();
// 'laravel'
markdown
{.collection-method}
markdown
方法将 GitHub 风格的 Markdown 转换为 HTML:
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 安全文档 (opens in a new tab),您可以使用 html_input
选项来转义或剥离原始 HTML,以及使用 allow_unsafe_links
选项来指定是否允许不安全的链接。如果您需要允许一些原始 HTML,您应该将您编译的 Markdown 通过 HTML 净化器:
use Illuminate\Support\Str;
Str::of('Inject: <script>alert("Hello XSS!");</script>')->markdown([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
// <p>Inject: alert("Hello XSS!");</p>
mask
{.collection-method}
mask
方法使用重复字符掩盖字符串的一部分,可用于混淆字符串的部分内容,如电子邮件地址和电话号码:
use Illuminate\Support\Str;
$string = Str::of('taylor@example.com')->mask('*', 3);
// tay***************
如果需要,您可以向 mask
方法提供负数值作为第三个或第四个参数,这将指示该方法从字符串的末尾开始在给定的距离处开始掩盖:
$string = Str::of('taylor@example.com')->mask('*', -15, 3);
// tay***@example.com
$string = Str::of('taylor@example.com')->mask('*', 4, -4);
// tayl**********.com
match
{.collection-method}
match
方法将返回字符串中与给定正则表达式模式匹配的部分:
use Illuminate\Support\Str;
$result = Str::of('foo bar')->match('/bar/');
// 'bar'
$result = Str::of('foo bar')->match('/foo (.*)/');
// 'bar'
matchAll
{.collection-method}
matchAll
方法将返回一个集合,其中包含字符串中与给定正则表达式模式匹配的部分:
use Illuminate\Support\Str;
$result = Str::of('bar foo bar')->matchAll('/bar/');
// collect(['bar', 'bar'])
如果您在表达式中指定了匹配组,Laravel 将返回第一个匹配组的匹配项的集合:
use Illuminate\Support\Str;
$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');
// collect(['un', 'ly']);
如果未找到匹配项,则将返回一个空集合。
isMatch
{.collection-method}
isMatch
方法如果字符串与给定的正则表达式匹配,则返回 true
:
use Illuminate\Support\Str;
$result = Str::of('foo bar')->isMatch('/foo (.*)/');
// true
$result = Str::of('laravel')->isMatch('/foo (.*)/');
// false
newLine
{.collection-method}
newLine
方法将一个“换行符”字符附加到字符串上:
use Illuminate\Support\Str;
$padded = Str::of('Laravel')->newLine()->append('Framework');
// 'Laravel
// Framework'
padBoth
{.collection-method}
padBoth
方法包装了 PHP 的 str_pad
函数,用另一个字符串填充字符串的两侧,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padBoth(10, '_');
// '__James___'
$padded = Str::of('James')->padBoth(10);
// ' James '
padLeft
{.collection-method}
padLeft
方法包装了 PHP 的 str_pad
函数,用另一个字符串填充字符串的左侧,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padLeft(10, '-=');
// '-=-=-James'
$padded = Str::of('James')->padLeft(10);
// ' James'
padRight
{.collection-method}
padRight
方法包装了 PHP 的 str_pad
函数,用另一个字符串填充字符串的右侧,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padRight(10, '-');
// 'James-----'
$padded = Str::of('James')->padRight(10);
// 'James '
pipe
{.collection-method}
pipe
方法允许您通过将字符串的当前值传递给给定的可调用对象来转换字符串:
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
{.collection-method}
plural
方法将单数单词字符串转换为其复数形式。此函数支持 Laravel 的复数器支持的任何语言:
use Illuminate\Support\Str;
$plural = Str::of('car')->plural();
// cars
$plural = Str::of('child')->plural();
// children
您可以向函数提供一个整数作为第二个参数,以检索字符串的单数或复数形式:
use Illuminate\Support\Str;
$plural = Str::of('child')->plural(2);
// children
$plural = Str::of('child')->plural(1);
// child
position
{.collection-method}
position
方法返回子串在字符串中首次出现的位置。如果子串不存在于字符串中,则返回 false
:
use Illuminate\Support\Str;
$position = Str::of('Hello, World!')->position('Hello');
// 0
$position = Str::of('Hello, World!')->position('W');
// 7
prepend
{.collection-method}
prepend
方法将给定的值前置到字符串上:
use Illuminate\Support\Str;
$string = Str::of('Framework')->prepend('Laravel ');
// Laravel Framework
remove
{.collection-method}
remove
方法从字符串中删除给定的值或值数组:
use Illuminate\Support\Str;
$string = Str::of('Arkansas is quite beautiful!')->remove('quite');
// Arkansas is beautiful!
您还可以将 false
作为第二个参数传递,以在删除字符串时忽略大小写。
repeat
{.collection-method}
repeat
方法重复给定的字符串:
use Illuminate\Support\Str;
$repeated = Str::of('a')->repeat(5);
// aaaaa
replace
{.collection-method}
replace
方法替换字符串中的给定字符串:
use Illuminate\Support\Str;
$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');
// Laravel 7.x
replace
方法还接受一个 caseSensitive
参数。默认情况下,replace
方法是区分大小写的:
$replaced = Str::of('macOS 13.x')->replace(
'macOS', 'iOS', caseSensitive: false
);
replaceArray
{.collection-method}
replaceArray
方法使用数组按顺序替换字符串中的给定值:
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
{.collection-method}
replaceFirst
方法替换字符串中给定值的首次出现:
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
{.collection-method}
replaceLast
方法替换字符串中给定值的最后一次出现:
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
{.collection-method}
replaceMatches
方法使用给定的替换字符串替换字符串中与模式匹配的所有部分:
use Illuminate\Support\Str;
$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')
// '15015551000'
replaceMatches
方法还接受一个闭包,该闭包将与字符串中与给定模式匹配的每个部分一起调用,允许您在闭包内执行替换逻辑并返回替换后的值:
use Illuminate\Support\Str;
$replaced = Str::of('123')->replaceMatches('/\d/', function (array $matches) {
return '['.$matches[0].']';
});
// '[1][2][3]'
replaceStart
{.collection-method}
replaceStart
方法仅在给定值出现在字符串开头时替换其首次出现:
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
{.collection-method}
replaceEnd
方法仅在给定值出现在字符串末尾时替换其最后一次出现:
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
{.collection-method}
scan
方法根据 sscanf
PHP 函数 (opens in a new tab)支持的格式将字符串的输入解析为一个集合:
use Illuminate\Support\Str;
$collection = Str::of('filename.jpg')->scan('%[^.].%s');
// collect(['filename', 'jpg'])
singular
{.collection-method}
singular
方法将字符串转换为其单数形式。此函数支持 Laravel 的复数器支持的任何语言:
use Illuminate\Support\Str;
$singular = Str::of('cars')->singular();
// car
$singular = Str::of('children')->singular();
// child
slug
{.collection-method}
slug
方法从给定的字符串生成一个对 URL 友好的“slug”:
use Illuminate\Support\Str;
$slug = Str::of('Laravel Framework')->slug('-');
// laravel-framework
snake
{.collection-method}
snake
方法将给定的字符串转换为 snake_case
:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->snake();
// foo_bar
split
{.collection-method}
split
方法使用正则表达式将字符串拆分为一个集合:
use Illuminate\Support\Str;
$segments = Str::of('one, two, three')->split('/[\s,]+/');
// collect(["one", "two", "three"])
squish
{.collection-method}
squish
方法从字符串中删除所有多余的空白字符,包括单词之间的多余空白字符:
use Illuminate\Support\Str;
$string = Str::of(' laravel framework ')->squish();
// laravel framework
start
{.collection-method}
start
方法如果字符串尚未以给定值开头,则将该值的单个实例添加到字符串中:
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->start('/');
// /this/string
$adjusted = Str::of('/this/string')->start('/');
// /this/string
startsWith
{.collection-method}
startsWith
方法判断给定的字符串是否以给定的值开头:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->startsWith('This');
// true
stripTags
{.collection-method}
stripTags
方法从字符串中删除所有 HTML 和 PHP 标签:
use Illuminate\Support\Str;
$result = Str::of('<a href="https://laravel.com">Taylor <b>Otwell</b></