Helpers
Introduction
Laravel 包含各种全局“帮助”PHP 函数。其中许多功能由框架本身使用;但是,如果您觉得方便,可以在自己的应用程序中自由使用它们。
可用方法
数组和对象
Arr::accessible Arr::add Arr::collapse Arr::crossJoin Arr::divide Arr::dot Arr::except Arr::exists Arr::first Arr::flatten Arr::forget Arr::get Arr::has Arr::hasAny Arr::isAssoc Arr::isList Arr::join Arr::keyBy Arr::last Arr::map Arr::only Arr::pluck Arr::prepend Arr::prependKeysWith Arr::pull Arr::query Arr::random Arr::set Arr::shuffle Arr::sort Arr::sortDesc Arr::sortRecursive Arr::toCssClasses Arr::undot Arr::where Arr::whereNotNull Arr::wrap data_fill data_get data_set head last
Paths
Strings
__ class_basename e preg_replace_array Str::after Str::afterLast Str::ascii Str::before Str::beforeLast Str::between Str::betweenFirst Str::camel Str::contains Str::containsAll Str::endsWith Str::excerpt Str::finish Str::headline Str::inlineMarkdown Str::is Str::isAscii Str::isJson Str::isUlid 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::random Str::remove Str::replace Str::replaceArray Str::replaceFirst Str::replaceLast 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::title Str::toHtmlString Str::ucfirst Str::ucsplit Str::upper Str::ulid Str::uuid Str::wordCount Str::words str trans trans_choice
流畅的弦乐
after afterLast append ascii basename before beforeLast between betweenFirst camel classBasename contains containsAll dirname endsWith excerpt exactly explode finish headline inlineMarkdown is isAscii isEmpty isNotEmpty isJson isUlid isUuid kebab lcfirst length limit lower ltrim markdown mask match matchAll newLine padBoth padLeft padRight pipe plural prepend remove replace replaceArray replaceFirst replaceLast replaceMatches rtrim scan singular slug snake split squish start startsWith studly substr substrReplace swap tap test title trim ucfirst ucsplit upper when whenContains whenContainsAll whenEmpty whenNotEmpty whenStartsWith whenEndsWith whenExactly whenNotExactly whenIs whenIsAscii whenIsUlid whenIsUuid whenTest wordCount words
URLs
Miscellaneous
abort abort_if abort_unless app auth back bcrypt blank broadcast cache class_uses_recursive collect config cookie csrf_field csrf_token decrypt dd dispatch dump encrypt env event fake filled info logger method_field now old optional policy redirect report report_if report_unless request rescue resolve response retry session tap throw_if throw_unless today trait_uses_recursive transform validator value view with
方法列表
数组和对象
Arr::accessible()
这Arr::accessible
方法确定给定值是否可访问数组:
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);
// true
$isAccessible = Arr::accessible(new Collection);
// true
$isAccessible = Arr::accessible('abc');
// false
$isAccessible = Arr::accessible(new stdClass);
// false
Arr::add()
这Arr::add
如果给定键在数组中不存在或设置为,则方法将给定键/值对添加到数组null
:
use Illuminate\Support\Arr;
$array = Arr::add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
Arr::collapse()
这Arr::collapse
方法将数组的数组折叠成一个数组:
use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr::crossJoin()
这Arr::crossJoin
方法交叉连接给定的数组,返回具有所有可能排列的笛卡尔积:
use Illuminate\Support\Arr;
$matrix = Arr::crossJoin([1, 2], ['a', 'b']);
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
Arr::divide()
这Arr::divide
方法返回两个数组:一个包含键,另一个包含给定数组的值:
use Illuminate\Support\Arr;
[$keys, $values] = Arr::divide(['name' => 'Desk']);
// $keys: ['name']
// $values: ['Desk']
Arr::dot()
这Arr::dot
方法将多维数组展平为使用“点”符号表示深度的单级数组:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$flattened = Arr::dot($array);
// ['products.desk.price' => 100]
Arr::except()
这Arr::except
方法从数组中删除给定的键/值对:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$filtered = Arr::except($array, ['price']);
// ['name' => 'Desk']
Arr::exists()
这Arr::exists
方法检查给定的键是否存在于提供的数组中:
use Illuminate\Support\Arr;
$array = ['name' => 'John Doe', 'age' => 17];
$exists = Arr::exists($array, 'name');
// true
$exists = Arr::exists($array, 'salary');
// false
Arr::first()
这Arr::first
方法返回通过给定真值测试的数组的第一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300];
$first = Arr::first($array, function (int $value, int $key) {
return $value >= 150;
});
// 200
默认值也可以作为第三个参数传递给该方法。如果没有值通过真值测试,将返回此值:
use Illuminate\Support\Arr;
$first = Arr::first($array, $callback, $default);
Arr::flatten()
这Arr::flatten
方法将多维数组展平为单级数组:
use Illuminate\Support\Arr;
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$flattened = Arr::flatten($array);
// ['Joe', 'PHP', 'Ruby']
Arr::forget()
这Arr::forget
方法使用“点”表示法从深度嵌套的数组中删除给定的键/值对:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::forget($array, 'products.desk');
// ['products' => []]
Arr::get()
这Arr::get
方法使用“点”表示法从深度嵌套的数组中检索值:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
$price = Arr::get($array, 'products.desk.price');
// 100
这Arr::get
方法还接受一个默认值,如果数组中不存在指定的键,则返回该值:
use Illuminate\Support\Arr;
$discount = Arr::get($array, 'products.desk.discount', 0);
// 0
Arr::has()
这Arr::has
方法使用“点”表示法检查数组中是否存在一个或多个给定项目:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::has($array, 'product.name');
// true
$contains = Arr::has($array, ['product.price', 'product.discount']);
// false
Arr::hasAny()
这Arr::hasAny
方法使用“点”表示法检查给定集合中的任何项目是否存在于数组中:
use Illuminate\Support\Arr;
$array = ['product' => ['name' => 'Desk', 'price' => 100]];
$contains = Arr::hasAny($array, 'product.name');
// true
$contains = Arr::hasAny($array, ['product.name', 'product.discount']);
// true
$contains = Arr::hasAny($array, ['category', 'product.discount']);
// false
Arr::isAssoc()
这Arr::isAssoc
方法返回true
如果给定数组是关联数组。如果一个数组没有以零开头的顺序数字键,则它被认为是“关联的”:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// false
Arr::isList()
这Arr::isList
方法返回true
如果给定数组的键是从零开始的连续整数:
use Illuminate\Support\Arr;
$isList = Arr::isList(['foo', 'bar', 'baz']);
// true
$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);
// false
Arr::join()
这Arr::join
方法将数组元素与字符串连接起来。使用此方法的第二个参数,您还可以为数组的最后一个元素指定连接字符串:
use Illuminate\Support\Arr;
$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];
$joined = Arr::join($array, ', ');
// Tailwind, Alpine, Laravel, Livewire
$joined = Arr::join($array, ', ', ' and ');
// Tailwind, Alpine, Laravel and Livewire
Arr::keyBy()
这Arr::keyBy
方法通过给定的键对数组进行键控。如果多个项目具有相同的键,则只有最后一个项目会出现在新数组中:
use Illuminate\Support\Arr;
$array = [
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
];
$keyed = Arr::keyBy($array, 'product_id');
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
Arr::last()
这Arr::last
方法返回通过给定真值测试的数组的最后一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function (int $value, int $key) {
return $value >= 150;
});
// 300
默认值可以作为第三个参数传递给该方法。如果没有值通过真值测试,将返回此值:
use Illuminate\Support\Arr;
$last = Arr::last($array, $callback, $default);
Arr::map()
这Arr::map
方法遍历数组并将每个值和键传递给给定的回调。数组值被回调返回的值替换:
use Illuminate\Support\Arr;
$array = ['first' => 'james', 'last' => 'kirk'];
$mapped = Arr::map($array, function (string $value, string $key) {
return ucfirst($value);
});
// ['first' => 'James', 'last' => 'Kirk']
Arr::only()
这Arr::only
方法仅返回给定数组中指定的键/值对:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = Arr::only($array, ['name', 'price']);
// ['name' => 'Desk', 'price' => 100]
Arr::pluck()
这Arr::pluck
方法从数组中检索给定键的所有值:
use Illuminate\Support\Arr;
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$names = Arr::pluck($array, 'developer.name');
// ['Taylor', 'Abigail']
您还可以指定您希望如何键入结果列表:
use Illuminate\Support\Arr;
$names = Arr::pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail']
Arr::prepend()
这Arr::prepend
方法会将一个项目推到数组的开头:
use Illuminate\Support\Arr;
$array = ['one', 'two', 'three', 'four'];
$array = Arr::prepend($array, 'zero');
// ['zero', 'one', 'two', 'three', 'four']
如果需要,您可以指定应用于该值的键:
use Illuminate\Support\Arr;
$array = ['price' => 100];
$array = Arr::prepend($array, 'Desk', 'name');
// ['name' => 'Desk', 'price' => 100]
Arr::prependKeysWith()
这Arr::prependKeysWith
用给定的前缀为关联数组的所有键名添加前缀:
use Illuminate\Support\Arr;
$array = [
'name' => 'Desk',
'price' => 100,
];
$keyed = Arr::prependKeysWith($array, 'product.');
/*
[
'product.name' => 'Desk',
'product.price' => 100,
]
*/
Arr::pull()
这Arr::pull
方法返回并从数组中删除键/值对:
use Illuminate\Support\Arr;
$array = ['name' => 'Desk', 'price' => 100];
$name = Arr::pull($array, 'name');
// $name: Desk
// $array: ['price' => 100]
默认值可以作为第三个参数传递给该方法。如果密钥不存在,将返回此值:
use Illuminate\Support\Arr;
$value = Arr::pull($array, $key, $default);
Arr::query()
这Arr::query
方法将数组转换为查询字符串:
use Illuminate\Support\Arr;
$array = [
'name' => 'Taylor',
'order' => [
'column' => 'created_at',
'direction' => 'desc'
]
];
Arr::query($array);
// name=Taylor&order[column]=created_at&order[direction]=desc
Arr::random()
这Arr::random
方法从数组中返回一个随机值:
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (retrieved randomly)
您还可以指定要返回的项目数作为可选的第二个参数。请注意,提供此参数将返回一个数组,即使只需要一个项目也是如此:
use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (retrieved randomly)
Arr::set()
这Arr::set
方法使用“点”表示法在深度嵌套的数组中设置一个值:
use Illuminate\Support\Arr;
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::set($array, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
Arr::shuffle()
这Arr::shuffle
方法随机打乱数组中的项目:
use Illuminate\Support\Arr;
$array = Arr::shuffle([1, 2, 3, 4, 5]);
// [3, 2, 5, 1, 4] - (generated randomly)
Arr::sort()
这Arr::sort
方法按值对数组进行排序:
use Illuminate\Support\Arr;
$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sort($array);
// ['Chair', 'Desk', 'Table']
您还可以根据给定闭包的结果对数组进行排序:
use Illuminate\Support\Arr;
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];
$sorted = array_values(Arr::sort($array, function (array $value) {
return $value['name'];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/
Arr::sortDesc()
这Arr::sortDesc
方法按值降序对数组进行排序:
use Illuminate\Support\Arr;
$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sortDesc($array);
// ['Table', 'Desk', 'Chair']
您还可以根据给定闭包的结果对数组进行排序:
use Illuminate\Support\Arr;
$array = [
['name' => 'Desk'],
['name' => 'Table'],
['name' => 'Chair'],
];
$sorted = array_values(Arr::sortDesc($array, function (array $value) {
return $value['name'];
}));
/*
[
['name' => 'Table'],
['name' => 'Desk'],
['name' => 'Chair'],
]
*/
Arr::sortRecursive()
这Arr::sortRecursive
方法使用递归排序数组sort
数值索引子数组的函数和ksort
关联子数组的函数:
use Illuminate\Support\Arr;
$array = [
['Roman', 'Taylor', 'Li'],
['PHP', 'Ruby', 'JavaScript'],
['one' => 1, 'two' => 2, 'three' => 3],
];
$sorted = Arr::sortRecursive($array);
/*
[
['JavaScript', 'PHP', 'Ruby'],
['one' => 1, 'three' => 3, 'two' => 2],
['Li', 'Roman', 'Taylor'],
]
*/
Arr::toCssClasses()
这Arr::toCssClasses
有条件地编译 CSS 类字符串。该方法接受一个类数组,其中数组键包含您要添加的一个或多个类,而值是一个布尔表达式。如果数组元素有数字键,它将始终包含在呈现的类列表中:
use Illuminate\Support\Arr;
$isActive = false;
$hasError = true;
$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];
$classes = Arr::toCssClasses($array);
/*
'p-4 bg-red'
*/
这个方法支持 Laravel 的功能,允许将类与 Blade 组件的属性包合并 以及@class
刀片指令.
Arr::undot()
这Arr::undot
方法将使用“点”表示法的一维数组扩展为多维数组:
use Illuminate\Support\Arr;
$array = [
'user.name' => 'Kevin Malone',
'user.occupation' => 'Accountant',
];
$array = Arr::undot($array);
// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
Arr::where()
这Arr::where
方法使用给定的闭包过滤数组:
use Illuminate\Support\Arr;
$array = [100, '200', 300, '400', 500];
$filtered = Arr::where($array, function (string|int $value, int $key) {
return is_string($value);
});
// [1 => '200', 3 => '400']
Arr::whereNotNull()
这Arr::whereNotNull
方法删除所有null
来自给定数组的值:
use Illuminate\Support\Arr;
$array = [0, null];
$filtered = Arr::whereNotNull($array);
// [0 => 0]
Arr::wrap()
这Arr::wrap
方法将给定值包装在数组中。如果给定的值已经是一个数组,它将不加修改地返回:
use Illuminate\Support\Arr;
$string = 'Laravel';
$array = Arr::wrap($string);
// ['Laravel']
如果给定值是null
,将返回一个空数组:
use Illuminate\Support\Arr;
$array = Arr::wrap(null);
// []
data_fill()
这data_fill
函数使用“点”表示法在嵌套数组或对象中设置缺失值:
$data = ['products' => ['desk' => ['price' => 100]]];
data_fill($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 100]]]
data_fill($data, 'products.desk.discount', 10);
// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
此函数还接受星号作为通配符,并相应地填充目标:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2'],
],
];
data_fill($data, 'products.*.price', 200);
/*
[
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 200],
],
]
*/
data_get()
这data_get
函数使用“点”表示法从嵌套数组或对象中检索值:
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
// 100
这data_get
函数还接受一个默认值,如果找不到指定的键,将返回该值:
$discount = data_get($data, 'products.desk.discount', 0);
// 0
该函数还接受使用星号的通配符,它可以针对数组或对象的任何键:
$data = [
'product-one' => ['name' => 'Desk 1', 'price' => 100],
'product-two' => ['name' => 'Desk 2', 'price' => 150],
];
data_get($data, '*.name');
// ['Desk 1', 'Desk 2'];
data_set()
这data_set
函数使用“点”表示法在嵌套数组或对象中设置一个值:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
此函数还接受使用星号的通配符,并将相应地在目标上设置值:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];
data_set($data, 'products.*.price', 200);
/*
[
'products' => [
['name' => 'Desk 1', 'price' => 200],
['name' => 'Desk 2', 'price' => 200],
],
]
*/
默认情况下,任何现有值都会被覆盖。如果你只想设置一个不存在的值,你可以通过false
作为函数的第四个参数:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, overwrite: false);
// ['products' => ['desk' => ['price' => 100]]]
head()
这head
函数返回给定数组中的第一个元素:
$array = [100, 200, 300];
$first = head($array);
// 100
last()
这last
函数返回给定数组中的最后一个元素:
$array = [100, 200, 300];
$last = last($array);
// 300
Paths
app_path()
这app_path
函数返回应用程序的完全限定路径app
目录。您也可以使用app_path
函数生成相对于应用程序目录的文件的完全限定路径:
$path = app_path();
$path = app_path('Http/Controllers/Controller.php');
base_path()
这base_path
函数返回应用程序根目录的完全限定路径。您也可以使用base_path
函数生成相对于项目根目录的给定文件的完全限定路径:
$path = base_path();
$path = base_path('vendor/bin');
config_path()
这config_path
函数返回应用程序的完全限定路径config
目录。您也可以使用config_path
函数生成应用程序配置目录中给定文件的完全限定路径:
$path = config_path();
$path = config_path('app.php');
database_path()
这database_path
函数返回应用程序的完全限定路径database
目录。您也可以使用database_path
函数生成数据库目录中给定文件的完全限定路径:
$path = database_path();
$path = database_path('factories/UserFactory.php');
lang_path()
这lang_path
函数返回应用程序的完全限定路径lang
目录。您也可以使用lang_path
函数生成目录中给定文件的完全限定路径:
$path = lang_path();
$path = lang_path('en/messages.php');
Note 默认情况下,Laravel 应用程序框架不包括
lang
目录。如果你想自定义 Laravel 的语言文件,你可以通过lang:publish
工匠命令。
mix()
这mix
函数返回一个路径版本化的 Mix 文件:
$path = mix('css/app.css');
public_path()
这public_path
函数返回应用程序的完全限定路径public
目录。您也可以使用public_path
函数生成公共目录中给定文件的完全限定路径:
$path = public_path();
$path = public_path('css/app.css');
resource_path()
这resource_path
函数返回应用程序的完全限定路径resources
目录。您也可以使用resource_path
函数生成资源目录中给定文件的完全限定路径:
$path = resource_path();
$path = resource_path('sass/app.scss');
storage_path()
这storage_path
函数返回应用程序的完全限定路径storage
目录。您也可以使用storage_path
函数生成存储目录中给定文件的完全限定路径:
$path = storage_path();
$path = storage_path('app/file.txt');
Strings
__()
这__
函数使用您的翻译给定的翻译字符串或翻译键语言文件:
echo __('Welcome to our application');
echo __('messages.welcome');
如果指定的翻译字符串或键不存在,则__
函数将返回给定的值。所以,使用上面的例子,__
函数会返回messages.welcome
如果该翻译键不存在。
class_basename()
这class_basename
函数返回给定类的类名,删除了类的命名空间:
$class = class_basename('Foo\Bar\Baz');
// Baz
e()
这e
函数运行 PHP 的htmlspecialchars
功能与double_encode
选项设置为true
默认情况下:
echo e('<html>foo</html>');
// <html>foo</html>
preg_replace_array()
这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()
这Str::after
方法返回字符串中给定值之后的所有内容。如果字符串中不存在该值,则将返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::after('This is my name', 'This is');
// ' my name'
Str::afterLast()
这Str::afterLast
方法返回字符串中最后一次出现给定值之后的所有内容。如果字符串中不存在该值,则将返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');
// 'Controller'
Str::ascii()
这Str::ascii
方法将尝试将字符串音译为 ASCII 值:
use Illuminate\Support\Str;
$slice = Str::ascii('û');
// 'u'
Str::before()
这Str::before
方法返回字符串中给定值之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::before('This is my name', 'my name');
// 'This is '
Str::beforeLast()
这Str::beforeLast
方法返回字符串中最后一次出现给定值之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::beforeLast('This is my name', 'is');
// 'This '
Str::between()
这Str::between
方法返回两个值之间的字符串部分:
use Illuminate\Support\Str;
$slice = Str::between('This is my name', 'This', 'name');
// ' is my '
Str::betweenFirst()
这Str::betweenFirst
方法返回两个值之间字符串的最小可能部分:
use Illuminate\Support\Str;
$slice = Str::betweenFirst('[a] bc [d]', '[', ']');
// 'a'
Str::camel()
这Str::camel
方法将给定的字符串转换为camelCase
:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
Str::contains()
这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
Str::containsAll()
这Str::containsAll
方法确定给定字符串是否包含给定数组中的所有值:
use Illuminate\Support\Str;
$containsAll = Str::containsAll('This is my name', ['my', 'name']);
// true
Str::endsWith()
这Str::endsWith
方法确定给定字符串是否以给定值结尾:
use Illuminate\Support\Str;
$result = Str::endsWith('This is my name', 'name');
// true
您还可以传递一个值数组来确定给定字符串是否以数组中的任何值结尾:
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
方法从给定字符串中提取与该字符串中短语的第一个实例匹配的摘录:
use Illuminate\Support\Str;
$excerpt = Str::excerpt('This is my name', 'my', [
'radius' => 3
]);
// '...is my na...'
这radius
选项,默认为100
, 允许您定义应出现在截断字符串每一侧的字符数。
此外,您可以使用omission
选项来定义将被添加到截断字符串之前和附加的字符串:
use Illuminate\Support\Str;
$excerpt = Str::excerpt('This is my name', 'name', [
'radius' => 3,
'omission' => '(...) '
]);
// '(...) my name'
Str::finish()
这Str::finish
方法将给定值的单个实例添加到字符串(如果它尚未以该值结尾):
use Illuminate\Support\Str;
$adjusted = Str::finish('this/string', '/');
// this/string/
$adjusted = Str::finish('this/string/', '/');
// this/string/
Str::headline()
这Str::headline
方法会将由大小写、连字符或下划线分隔的字符串转换为空格分隔的字符串,每个单词的第一个字母大写:
use Illuminate\Support\Str;
$headline = Str::headline('steve_jobs');
// Steve Jobs
$headline = Str::headline('EmailNotificationSent');
// Email Notification Sent
Str::inlineMarkdown()
这Str::inlineMarkdown
方法将 GitHub 风格的 Markdown 转换为内联 HTML,使用CommonMark.然而,不同于markdown
方法,它不会将所有生成的 HTML 包装在块级元素中:
use Illuminate\Support\Str;
$html = Str::inlineMarkdown('**Laravel**');
// <strong>Laravel</strong>
Str::is()
这Str::is
方法确定给定字符串是否与给定模式匹配。星号可用作通配符值:
use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// false
Str::isAscii()
这Str::isAscii
方法确定给定字符串是否为 7 位 ASCII:
use Illuminate\Support\Str;
$isAscii = Str::isAscii('Taylor');
// true
$isAscii = Str::isAscii('ü');
// false
Str::isJson()
这Str::isJson
方法确定给定的字符串是否是有效的 JSON:
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::isUlid()
这Str::isUlid
方法确定给定的字符串是否是有效的 ULID:
use Illuminate\Support\Str;
$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');
// true
$isUlid = Str::isUlid('laravel');
// false
Str::isUuid()
这Str::isUuid
方法确定给定的字符串是否是有效的 UUID:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
// true
$isUuid = Str::isUuid('laravel');
// false
Str::kebab()
这Str::kebab
方法将给定的字符串转换为kebab-case
:
use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-bar
Str::lcfirst()
这Str::lcfirst
方法返回第一个字符小写的给定字符串:
use Illuminate\Support\Str;
$string = Str::lcfirst('Foo Bar');
// foo Bar
Str::length()
这Str::length
方法返回给定字符串的长度:
use Illuminate\Support\Str;
$length = Str::length('Laravel');
// 7
Str::limit()
这Str::limit
方法将给定字符串截断为指定长度:
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);
// The quick brown fox...
您可以将第三个参数传递给该方法以更改将附加到截断字符串末尾的字符串:
use Illuminate\Support\Str;
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');
// The quick brown fox (...)
Str::lower()
这Str::lower
方法将给定的字符串转换为小写:
use Illuminate\Support\Str;
$converted = Str::lower('LARAVEL');
// laravel
Str::markdown()
这Str::markdown
方法使用 GitHub 风格的 Markdown 转换成 HTMLCommonMark:
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>
Str::mask()
这Str::mask
方法用重复字符屏蔽部分字符串,可用于混淆字符串段,例如电子邮件地址和电话号码:
use Illuminate\Support\Str;
$string = Str::mask('taylor@example.com', '*', 3);
// tay***************
如果需要,您可以提供一个负数作为第三个参数mask
方法,它将指示该方法在距离字符串末尾的给定距离处开始屏蔽:
$string = Str::mask('taylor@example.com', '*', -15, 3);
// tay***@example.com
Str::orderedUuid()
这Str::orderedUuid
方法生成一个“时间戳优先”的 UUID,该 UUID 可以有效地存储在索引数据库列中。使用此方法生成的每个 UUID 将排在先前使用此方法生成的 UUID 之后:
use Illuminate\Support\Str;
return (string) Str::orderedUuid();
Str::padBoth()
这Str::padBoth
方法包装 PHP 的str_pad
函数,用另一个字符串填充字符串的两边,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::padBoth('James', 10, '_');
// '__James___'
$padded = Str::padBoth('James', 10);
// ' James '
Str::padLeft()
这Str::padLeft
方法包装 PHP 的str_pad
函数,用另一个字符串填充字符串的左侧,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::padLeft('James', 10, '-=');
// '-=-=-James'
$padded = Str::padLeft('James', 10);
// ' James'
Str::padRight()
这Str::padRight
方法包装 PHP 的str_pad
函数,用另一个字符串填充字符串的右侧,直到最终字符串达到所需的长度:
use Illuminate\Support\Str;
$padded = Str::padRight('James', 10, '-');
// 'James-----'
$padded = Str::padRight('James', 10);
// 'James '
Str::password()
这Str::password
方法可用于生成给定长度的安全随机密码。密码将由字母、数字、符号和空格的组合组成。默认情况下,密码长度为 32 个字符:
use Illuminate\Support\Str;
$password = Str::password();
// 'EbJo2vE-AS:U,$%_gkrV4n,q~1xy/-_4'
$password = Str::password(12);
// 'qwuar>#V|i]N'