辅助函数
介绍
Laravel 包含多种全局 "辅助" PHP 函数。许多这些函数被框架本身使用;然而,如果您觉得方便,您可以在自己的应用程序中使用它们。
可用方法
数组和对象
Arr::accessibleArr::addArr::collapseArr::crossJoinArr::divideArr::dotArr::exceptArr::existsArr::firstArr::flattenArr::forgetArr::getArr::hasArr::hasAnyArr::isAssocArr::lastArr::onlyArr::pluckArr::prependArr::pullArr::queryArr::randomArr::setArr::shuffleArr::sortArr::sortRecursiveArr::toCssClassesArr::undotArr::whereArr::whereNotNullArr::wrapdata_filldata_getdata_setheadlast
路径
字符串
__class_basenameepreg_replace_arrayStr::afterStr::afterLastStr::asciiStr::beforeStr::beforeLastStr::betweenStr::camelStr::containsStr::containsAllStr::endsWithStr::finishStr::headlineStr::isStr::isAsciiStr::isUuidStr::kebabStr::lengthStr::limitStr::lowerStr::markdownStr::maskStr::orderedUuidStr::padBothStr::padLeftStr::padRightStr::pluralStr::pluralStudlyStr::randomStr::removeStr::replaceStr::replaceArrayStr::replaceFirstStr::replaceLastStr::reverseStr::singularStr::slugStr::snakeStr::startStr::startsWithStr::studlyStr::substrStr::substrCountStr::substrReplaceStr::titleStr::toHtmlStringStr::ucfirstStr::upperStr::uuidStr::wordCountStr::wordstranstrans_choice
流畅字符串
afterafterLastappendasciibasenamebeforebeforeLastbetweencamelcontainscontainsAlldirnameendsWithexactlyexplodefinishisisAsciiisEmptyisNotEmptyisUuidkebablengthlimitlowerltrimmarkdownmaskmatchmatchAllpadBothpadLeftpadRightpipepluralprependremovereplacereplaceArrayreplaceFirstreplaceLastreplaceMatchesrtrimscansingularslugsnakesplitstartstartsWithstudlysubstrsubstrReplacetaptesttitletrimucfirstupperwhenwhenContainswhenContainsAllwhenEmptywhenNotEmptywhenStartsWithwhenEndsWithwhenExactlywhenIswhenIsAsciiwhenIsUuidwhenTestwordCountwords
URL
杂项
abortabort_ifabort_unlessappauthbackbcryptblankbroadcastcacheclass_uses_recursivecollectconfigcookiecsrf_fieldcsrf_tokendddispatchdumpenveventfilledinfologgermethod_fieldnowoldoptionalpolicyredirectreportrequestrescueresolveresponseretrysessiontapthrow_ifthrow_unlesstodaytrait_uses_recursivetransformvalidatorvalueviewwith
方法列表
数组和对象
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);
// falseArr::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');
// falseArr::first()
Arr::first 方法返回通过给定真值测试的数组的第一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300];
$first = Arr::first($array, function ($value, $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');
// 100Arr::get 方法还接受一个默认值,如果指定的键不存在于数组中,将返回此值:
use Illuminate\Support\Arr;
$discount = Arr::get($array, 'products.desk.discount', 0);
// 0Arr::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']);
// falseArr::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']);
// falseArr::isAssoc()
Arr::isAssoc 返回 true 如果给定数组是关联数组。如果数组没有从零开始的连续数字键,则认为它是 "关联" 的:
use Illuminate\Support\Arr;
$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);
// true
$isAssoc = Arr::isAssoc([1, 2, 3]);
// falseArr::last()
Arr::last 方法返回通过给定真值测试的数组的最后一个元素:
use Illuminate\Support\Arr;
$array = [100, 200, 300, 110];
$last = Arr::last($array, function ($value, $key) {
return $value >= 150;
});
// 300可以将默认值作为方法的第三个参数传递。如果没有值通过真值测试,将返回此值:
use Illuminate\Support\Arr;
$last = Arr::last($array, $callback, $default);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::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]=descArr::random()
Arr::random 方法从数组中返回一个随机值:
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (随机检索)您还可以指定要返回的项目数量作为可选的第二个参数。请注意,提供此参数将返回一个数组,即使只需要一个项目:
use Illuminate\Support\Arr;
$items = Arr::random($array, 2);
// [2, 5] - (随机检索)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] - (随机生成)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 ($value) {
return $value['name'];
}));
/*
[
['name' => 'Chair'],
['name' => 'Desk'],
['name' => 'Table'],
]
*/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 Blade 指令。
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 ($value, $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');
// 100data_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);
// 100last()
last 函数返回给定数组中的最后一个元素:
$array = [100, 200, 300];
$last = last($array);
// 300路径
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');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');字符串
__()
__ 函数使用您的 本地化文件 翻译给定的翻译字符串或翻译键:
echo __('Welcome to our application');
echo __('messages.welcome');如果指定的翻译字符串或键不存在,__ 函数将返回给定值。因此,使用上面的示例,如果该翻译键不存在,__ 函数将返回 messages.welcome。
class_basename()
class_basename 函数返回给定类的类名,并去除类的命名空间:
$class = class_basename('Foo\Bar\Baz');
// Baze()
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:00Str::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::camel()
Str::camel 方法将给定字符串转换为 camelCase:
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBarStr::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']);
// trueStr::containsAll()
Str::containsAll 方法确定给定字符串是否包含给定数组中的所有值:
use Illuminate\Support\Str;
$containsAll = Str::containsAll('This is my name', ['my', 'name']);
// trueStr::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']);
// falseStr::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 SentStr::is()
Str::is 方法确定给定字符串是否与给定模式匹配。星号可以用作通配符:
use Illuminate\Support\Str;
$matches = Str::is('foo*', 'foobar');
// true
$matches = Str::is('baz*', 'foobar');
// falseStr::isAscii()
Str::isAscii 方法确定给定字符串是否为 7 位 ASCII:
use Illuminate\Support\Str;
$isAscii = Str::isAscii('Taylor');
// true
$isAscii = Str::isAscii('ü');
// falseStr::isUuid()
Str::isUuid 方法确定给定字符串是否为有效的 UUID:
use Illuminate\Support\Str;
$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');
// true
$isUuid = Str::isUuid('laravel');
// falseStr::kebab()
Str::kebab 方法将给定字符串转换为 kebab-case:
use Illuminate\Support\Str;
$converted = Str::kebab('fooBar');
// foo-barStr::length()
Str::length 方法返回给定字符串的长度:
use Illuminate\Support\Str;
$length = Str::length('Laravel');
// 7Str::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');
// laravelStr::markdown()
Str::markdown 方法将 GitHub 风格的 Markdown 转换为 HTML:
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.comStr::orderedUuid()
Str::orderedUuid 方法生成一个 "时间戳优先" 的 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::plural()
Str::plural 方法将单数形式的单词字符串转换为其复数形式。此函数目前仅支持英语:
use Illuminate\Support\Str;
$plural = Str::plural('car');
// cars
$plural = Str::plural('child');
// children您可以提供一个整数作为函数的第二个参数,以获取字符串的单数或复数形式:
use Illuminate\Support\Str;
$plural = Str::plural('child', 2);
// children
$singular = Str::plural('child', 1);
// childStr::pluralStudly()
Str::pluralStudly 方法将以驼峰命名法格式的单数形式单词字符串转换为其复数形式。此函数目前仅支持英语:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman');
// VerifiedHumans
$plural = Str::pluralStudly('UserFeedback');
// UserFeedback您可以提供一个整数作为函数的第二个参数,以获取字符串的单数或复数形式:
use Illuminate\Support\Str;
$plural = Str::pluralStudly('VerifiedHuman', 2);
// VerifiedHumans
$singular = Str::pluralStudly('VerifiedHuman', 1);
// VerifiedHumanStr::random()
Str::random 方法生成指定长度的随机字符串。此函数使用 PHP 的 random_bytes 函数:
use Illuminate\Support\Str;
$random = Str::random(40);Str::remove()
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::replace()
Str::replace 方法替换字符串中的给定字符串:
use Illuminate\Support\Str;
$string = 'Laravel 8.x';
$replaced = Str::replace('8.x', '9.x', $string);
// Laravel 9.xStr::replaceArray()
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:00Str::replaceFirst()
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 dogStr::replaceLast()
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 dogStr::reverse()
Str::reverse 方法反转给定的字符串:
use Illuminate\Support\Str;
$reversed = Str::reverse('Hello World');
// dlroW olleHStr::singular()
Str::singular 方法将字符串转换为其单数形式。此函数目前仅支持英语:
use Illuminate\Support\Str;
$singular = Str::singular('cars');
// car
$singular = Str::singular('children');
// childStr::slug()
Str::slug 方法从给定字符串生成一个 URL 友好的“slug”:
use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');
// laravel-5-frameworkStr::snake()
Str::snake 方法将给定字符串转换为 snake_case:
use Illuminate\Support\Str;
$converted = Str::snake('fooBar');
// foo_bar
$converted = Str::snake('fooBar', '-');
// foo-barStr::start()
Str::start 方法在字符串前添加一个给定值的单个实例,如果它尚未以该值开头:
use Illuminate\Support\Str;
$adjusted = Str::start('this/string', '/');
// /this/string
$adjusted = Str::start('/this/string', '/');
// /this/stringStr::startsWith()
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']);
// trueStr::studly()
Str::studly 方法将给定字符串转换为 StudlyCase:
use Illuminate\Support\Str;
$converted = Str::studly('foo_bar');
// FooBarStr::substr()
Str::substr 方法返回由起始和长度参数指定的字符串部分:
use Illuminate\Support\Str;
$converted = Str::substr('The Laravel Framework', 4, 7);
// LaravelStr::substrCount()
Str::substrCount 方法返回给定字符串中给定值的出现次数:
use Illuminate\Support\Str;
$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');
// 2Str::substrReplace()
Str::substrReplace 方法替换字符串中某个部分的文本,从第三个参数指定的位置开始,并替换第四个参数指定的字符数。将 0 传递给方法的第四个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:
use Illuminate\Support\Str;
$result = Str::substrReplace('1300', ':', 2);
// 13:
$result = Str::substrReplace('1300', ':', 2, 0);
// 13:00Str::title()
Str::title 方法将给定字符串转换为 Title Case:
use Illuminate\Support\Str;
$converted = Str::title('a nice title uses the correct case');
// A Nice Title Uses The Correct CaseStr::toHtmlString()
Str::toHtmlString 方法将字符串实例转换为 Illuminate\Support\HtmlString 的实例,可以在 Blade 模板中显示:
use Illuminate\Support\Str;
$htmlString = Str::of('Nuno Maduro')->toHtmlString();Str::ucfirst()
Str::ucfirst 方法返回首字母大写的给定字符串:
use Illuminate\Support\Str;
$string = Str::ucfirst('foo bar');
// Foo barStr::upper()
Str::upper 方法将给定字符串转换为大写:
use Illuminate\Support\Str;
$string = Str::upper('laravel');
// LARAVELStr::uuid()
Str::uuid 方法生成一个 UUID(版本 4):
use Illuminate\Support\Str;
return (string) Str::uuid();Str::wordCount()
Str::wordCount 方法返回字符串包含的单词数量:
use Illuminate\Support\Str;
Str::wordCount('Hello, world!'); // 2Str::words()
Str::words 方法限制字符串中的单词数量。可以通过其第三个参数传递一个附加字符串,以指定应附加到截断字符串末尾的字符串:
use Illuminate\Support\Str;
return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// Perfectly balanced, as >>>trans()
trans 函数使用您的本地化文件翻译给定的翻译键:
echo trans('messages.welcome');如果指定的翻译键不存在,trans 函数将返回给定的键。因此,使用上面的示例,如果翻译键不存在,trans 函数将返回 messages.welcome。
trans_choice()
trans_choice 函数使用屈折翻译给定的翻译键:
echo trans_choice('messages.notifications', $unreadCount);如果指定的翻译键不存在,trans_choice 函数将返回给定的键。因此,使用上面的示例,如果翻译键不存在,trans_choice 函数将返回 messages.notifications。
流畅字符串
流畅字符串为处理字符串值提供了更流畅的面向对象接口,允许您使用比传统字符串操作更具可读性的语法来链接多个字符串操作。
after
after 方法返回字符串中给定值之后的所有内容。如果该值不存在于字符串中,则返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->after('This is');
// ' my name'afterLast
afterLast 方法返回字符串中最后一次出现的给定值之后的所有内容。如果该值不存在于字符串中,则返回整个字符串:
use Illuminate\Support\Str;
$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');
// 'Controller'append
append 方法将给定值附加到字符串:
use Illuminate\Support\Str;
$string = Str::of('Taylor')->append(' Otwell');
// 'Taylor Otwell'ascii
ascii 方法将尝试将字符串转写为 ASCII 值:
use Illuminate\Support\Str;
$string = Str::of('ü')->ascii();
// 'u'basename
basename 方法将返回给定字符串的尾部名称组件:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->basename();
// 'baz'如果需要,您可以提供一个“扩展名”,它将从尾部组件中移除:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');
// 'baz'before
before 方法返回字符串中给定值之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->before('my name');
// 'This is 'beforeLast
beforeLast 方法返回字符串中最后一次出现的给定值之前的所有内容:
use Illuminate\Support\Str;
$slice = Str::of('This is my name')->beforeLast('is');
// 'This 'between
between 方法返回字符串中两个值之间的部分:
use Illuminate\Support\Str;
$converted = Str::of('This is my name')->between('This', 'name');
// ' is my 'camel
camel 方法将给定字符串转换为 camelCase:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->camel();
// fooBarcontains
contains 方法确定给定字符串是否包含给定值。此方法区分大小写:
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains('my');
// true您还可以传递一个值数组,以确定给定字符串是否包含数组中的任何值:
use Illuminate\Support\Str;
$contains = Str::of('This is my name')->contains(['my', 'foo']);
// truecontainsAll
containsAll 方法确定给定字符串是否包含给定数组中的所有值:
use Illuminate\Support\Str;
$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);
// truedirname
dirname 方法返回给定字符串的父目录部分:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->dirname();
// '/foo/bar'如果需要,您可以指定要从字符串中修剪的目录级别数:
use Illuminate\Support\Str;
$string = Str::of('/foo/bar/baz')->dirname(2);
// '/foo'endsWith
endsWith 方法确定给定字符串是否以给定值结尾:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->endsWith('name');
// true您还可以传递一个值数组,以确定给定字符串是否以数组中的任何值结尾:
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']);
// falseexactly
exactly 方法确定给定字符串是否与另一个字符串完全匹配:
use Illuminate\Support\Str;
$result = Str::of('Laravel')->exactly('Laravel');
// trueexplode
explode 方法通过给定的分隔符拆分字符串,并返回一个包含拆分字符串每个部分的集合:
use Illuminate\Support\Str;
$collection = Str::of('foo bar baz')->explode(' ');
// collect(['foo', 'bar', 'baz'])finish
finish 方法在字符串末尾添加一个给定值的单个实例,如果它尚未以该值结尾:
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->finish('/');
// this/string/
$adjusted = Str::of('this/string/')->finish('/');
// this/string/is
is 方法确定给定字符串是否与给定模式匹配。星号可以用作通配符值:
use Illuminate\Support\Str;
$matches = Str::of('foobar')->is('foo*');
// true
$matches = Str::of('foobar')->is('baz*');
// falseisAscii
isAscii 方法确定给定字符串是否为 ASCII 字符串:
use Illuminate\Support\Str;
$result = Str::of('Taylor')->isAscii();
// true
$result = Str::of('ü')->isAscii();
// falseisEmpty
isEmpty 方法确定给定字符串是否为空:
use Illuminate\Support\Str;
$result = Str::of(' ')->trim()->isEmpty();
// true
$result = Str::of('Laravel')->trim()->isEmpty();
// falseisNotEmpty
isNotEmpty 方法确定给定字符串是否不为空:
use Illuminate\Support\Str;
$result = Str::of(' ')->trim()->isNotEmpty();
// false
$result = Str::of('Laravel')->trim()->isNotEmpty();
// trueisUuid
isUuid 方法确定给定字符串是否为 UUID:
use Illuminate\Support\Str;
$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();
// true
$result = Str::of('Taylor')->isUuid();
// falsekebab
kebab 方法将给定字符串转换为 kebab-case:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->kebab();
// foo-barlength
length 方法返回给定字符串的长度:
use Illuminate\Support\Str;
$length = Str::of('Laravel')->length();
// 7limit
limit 方法将给定字符串截断为指定长度:
use Illuminate\Support\Str;
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);
// The quick brown fox...您还可以传递第二个参数来更改将附加到截断字符串末尾的字符串:
use Illuminate\Support\Str;
$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');
// The quick brown fox (...)lower
lower 方法将给定字符串转换为小写:
use Illuminate\Support\Str;
$result = Str::of('LARAVEL')->lower();
// 'laravel'ltrim
ltrim 方法修剪字符串的左侧:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->ltrim();
// 'Laravel '
$string = Str::of('/Laravel/')->ltrim('/');
// 'Laravel/'markdown
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>mask
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.commatch
match 方法将返回与给定正则表达式模式匹配的字符串部分:
use Illuminate\Support\Str;
$result = Str::of('foo bar')->match('/bar/');
// 'bar'
$result = Str::of('foo bar')->match('/foo (.*)/');
// 'bar'matchAll
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']);如果未找到匹配项,将返回一个空集合。
padBoth
padBoth 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的两侧,直到最终字符串达到所需长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padBoth(10, '_');
// '__James___'
$padded = Str::of('James')->padBoth(10);
// ' James 'padLeft
padLeft 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的左侧,直到最终字符串达到所需长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padLeft(10, '-=');
// '-=-=-James'
$padded = Str::of('James')->padLeft(10);
// ' James'padRight
padRight 方法包装 PHP 的 str_pad 函数,用另一个字符串填充字符串的右侧,直到最终字符串达到所需长度:
use Illuminate\Support\Str;
$padded = Str::of('James')->padRight(10, '-');
// 'James-----'
$padded = Str::of('James')->padRight(10);
// 'James 'pipe
pipe 方法允许您通过将其当前值传递给给定的可调用对象来转换字符串:
use Illuminate\Support\Str;
$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');
// 'Checksum: a5c95b86291ea299fcbe64458ed12702'
$closure = Str::of('foo')->pipe(function ($str) {
return 'bar';
});
// 'bar'plural
plural 方法将单数形式的单词字符串转换为其复数形式。此函数目前仅支持英语:
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);
// childprepend
prepend 方法将给定值附加到字符串的开头:
use Illuminate\Support\Str;
$string = Str::of('Framework')->prepend('Laravel ');
// Laravel Frameworkremove
remove 方法从字符串中移除给定的值或值数组:
use Illuminate\Support\Str;
$string = Str::of('Arkansas is quite beautiful!')->remove('quite');
// Arkansas is beautiful!您还可以将 false 作为第二个参数传递,以在移除字符串时忽略大小写。
replace
replace 方法替换字符串中的给定字符串:
use Illuminate\Support\Str;
$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');
// Laravel 7.xreplaceArray
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:00replaceFirst
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 dogreplaceLast
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 dogreplaceMatches
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 ($match) {
return '['.$match[0].']';
});
// '[1][2][3]'rtrim
rtrim 方法修剪给定字符串的右侧:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->rtrim();
// ' Laravel'
$string = Str::of('/Laravel/')->rtrim('/');
// '/Laravel'scan
scan 方法根据 sscanf PHP 函数支持的格式从字符串中解析输入为集合:
use Illuminate\Support\Str;
$collection = Str::of('filename.jpg')->scan('%[^.].%s');
// collect(['filename', 'jpg'])singular
singular 方法将字符串转换为其单数形式。此函数目前仅支持英语:
use Illuminate\Support\Str;
$singular = Str::of('cars')->singular();
// car
$singular = Str::of('children')->singular();
// childslug
slug 方法从给定字符串生成一个 URL 友好的“slug”:
use Illuminate\Support\Str;
$slug = Str::of('Laravel Framework')->slug('-');
// laravel-frameworksnake
snake 方法将给定字符串转换为 snake_case:
use Illuminate\Support\Str;
$converted = Str::of('fooBar')->snake();
// foo_barsplit
split 方法使用正则表达式将字符串拆分为集合:
use Illuminate\Support\Str;
$segments = Str::of('one, two, three')->split('/[\s,]+/');
// collect(["one", "two", "three"])start
start 方法在字符串前添加一个给定值的单个实例,如果它尚未以该值开头:
use Illuminate\Support\Str;
$adjusted = Str::of('this/string')->start('/');
// /this/string
$adjusted = Str::of('/this/string')->start('/');
// /this/stringstartsWith
startsWith 方法确定给定字符串是否以给定值开头:
use Illuminate\Support\Str;
$result = Str::of('This is my name')->startsWith('This');
// truestudly
studly 方法将给定字符串转换为 StudlyCase:
use Illuminate\Support\Str;
$converted = Str::of('foo_bar')->studly();
// FooBarsubstr
substr 方法返回由给定起始和长度参数指定的字符串部分:
use Illuminate\Support\Str;
$string = Str::of('Laravel Framework')->substr(8);
// Framework
$string = Str::of('Laravel Framework')->substr(8, 5);
// FramesubstrReplace
substrReplace 方法替换字符串中某个部分的文本,从第三个参数指定的位置开始,并替换第四个参数指定的字符数。将 0 传递给方法的第四个参数将在指定位置插入字符串,而不替换字符串中的任何现有字符:
use Illuminate\Support\Str;
$string = Str::of('1300')->substrReplace(':', 2);
// 13:
$string = Str::of('The Framework')->substrReplace(' Laravel', 3, 0);
// The Laravel Frameworktap
tap 方法将字符串传递给给定的闭包,允许您检查和与字符串交互,而不影响字符串本身。无论闭包返回什么,tap 方法都会返回原始字符串:
use Illuminate\Support\Str;
$string = Str::of('Laravel')
->append(' Framework')
->tap(function ($string) {
dump('String after append: ' . $string);
})
->upper();
// LARAVEL FRAMEWORKtest
test 方法确定字符串是否与给定的正则表达式模式匹配:
use Illuminate\Support\Str;
$result = Str::of('Laravel Framework')->test('/Laravel/');
// truetitle
title 方法将给定字符串转换为 Title Case:
use Illuminate\Support\Str;
$converted = Str::of('a nice title uses the correct case')->title();
// A Nice Title Uses The Correct Casetrim
trim 方法修剪给定字符串:
use Illuminate\Support\Str;
$string = Str::of(' Laravel ')->trim();
// 'Laravel'
$string = Str::of('/Laravel/')->trim('/');
// 'Laravel'ucfirst
ucfirst 方法返回首字母大写的给定字符串:
use Illuminate\Support\Str;
$string = Str::of('foo bar')->ucfirst();
// Foo barupper
upper 方法将给定字符串转换为大写:
use Illuminate\Support\Str;
$adjusted = Str::of('laravel')->upper();
// LARAVELwhen
when 方法在给定条件为 true 时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('Taylor')
->when(true, function ($string) {
return $string->append(' Otwell');
});
// 'Taylor Otwell'如果需要,您可以将另一个闭包作为 when 方法的第三个参数传递。如果条件参数计算为 false,则此闭包将执行。
whenContains
whenContains 方法在字符串包含给定值时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('tony stark')
->whenContains('tony', function ($string) {
return $string->title();
});
// 'Tony Stark'如果需要,您可以将另一个闭包作为 when 方法的第三个参数传递。如果字符串不包含给定值,则此闭包将执行。
您还可以传递一个值数组,以确定给定字符串是否包含数组中的任何值:
use Illuminate\Support\Str;
$string = Str::of('tony stark')
->whenContains(['tony', 'hulk'], function ($string) {
return $string->title();
});
// Tony StarkwhenContainsAll
whenContainsAll 方法在字符串包含所有给定子字符串时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('tony stark')
->whenContainsAll(['tony', 'stark'], function ($string) {
return $string->title();
});
// 'Tony Stark'如果需要,您可以将另一个闭包作为 when 方法的第三个参数传递。如果条件参数计算为 false,则此闭包将执行。
whenEmpty
whenEmpty 方法在字符串为空时调用给定的闭包。如果闭包返回一个值,则该值也将由 whenEmpty 方法返回。如果闭包不返回值,则返回流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of(' ')->whenEmpty(function ($string) {
return $string->trim()->prepend('Laravel');
});
// 'Laravel'whenNotEmpty
whenNotEmpty 方法在字符串不为空时调用给定的闭包。如果闭包返回一个值,则该值也将由 whenNotEmpty 方法返回。如果闭包不返回值,则返回流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('Framework')->whenNotEmpty(function ($string) {
return $string->prepend('Laravel ');
});
// 'Laravel Framework'whenStartsWith
whenStartsWith 方法在字符串以给定子字符串开头时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('disney world')->whenStartsWith('disney', function ($string) {
return $string->title();
});
// 'Disney World'whenEndsWith
whenEndsWith 方法在字符串以给定子字符串结尾时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('disney world')->whenEndsWith('world', function ($string) {
return $string->title();
});
// 'Disney World'whenExactly
whenExactly 方法在字符串与给定字符串完全匹配时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('laravel')->whenExactly('laravel', function ($string) {
return $string->title();
});
// 'Laravel'whenIs
whenIs 方法在字符串与给定模式匹配时调用给定的闭包。星号可以用作通配符值。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('foo/bar')->whenIs('foo/*', function ($string) {
return $string->append('/baz');
});
// 'foo/bar/baz'whenIsAscii
whenIsAscii 方法在字符串为 7 位 ASCII 时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('foo/bar')->whenIsAscii('laravel', function ($string) {
return $string->title();
});
// 'Laravel'whenIsUuid
whenIsUuid 方法在字符串为有效的 UUID 时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('foo/bar')->whenIsUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de', function ($string) {
return $string->substr(0, 8);
});
// 'a0a2a2d2'whenTest
whenTest 方法在字符串与给定正则表达式匹配时调用给定的闭包。闭包将接收流畅的字符串实例:
use Illuminate\Support\Str;
$string = Str::of('laravel framework')->whenTest('/laravel/', function ($string) {
return $string->title();
});
// 'Laravel Framework'wordCount
wordCount 方法返回字符串包含的单词数量:
use Illuminate\Support\Str;
Str::of('Hello, world!')->wordCount(); // 2words
words 方法限制字符串中的单词数量。如果需要,您可以指定一个附加字符串,该字符串将附加到截断字符串的末尾:
use Illuminate\Support\Str;
$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');
// Perfectly balanced, as >>>URLs
action()
action 函数为给定的控制器操作生成一个 URL:
use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);如果方法接受路由参数,您可以将它们作为方法的第二个参数传递:
$url = action([UserController::class, 'profile'], ['id' => 1]);asset()
asset 函数使用请求的当前方案(HTTP 或 HTTPS)为资产生成一个 URL:
$url = asset('img/photo.jpg');您可以通过在 .env 文件中设置 ASSET_URL 变量来配置资产 URL 主机。如果您在外部服务(如 Amazon S3 或其他 CDN)上托管资产,这可能很有用:
// ASSET_URL=http://example.com/assets
$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpgroute()
route 函数为给定的命名路由生成一个 URL:
$url = route('route.name');如果路由接受参数,您可以将它们作为函数的第二个参数传递:
$url = route('route.name', ['id' => 1]);默认情况下,route 函数生成一个绝对 URL。如果您希望生成相对 URL,可以将 false 作为函数的第三个参数传递:
$url = route('route.name', ['id' => 1], false);secure_asset()
secure_asset 函数使用 HTTPS 为资产生成一个 URL:
$url = secure_asset('img/photo.jpg');secure_url()
secure_url 函数为给定路径生成一个完全合格的 HTTPS URL。可以在函数的第二个参数中传递附加的 URL 段:
$url = secure_url('user/profile');
$url = secure_url('user/profile', [1]);url()
url 函数为给定路径生成一个完全合格的 URL:
$url = url('user/profile');
$url = url('user/profile', [1]);如果未提供路径,则返回一个 Illuminate\Routing\UrlGenerator 实例:
$current = url()->current();
$full = url()->full();
$previous = url()->previous();杂项
abort()
abort 函数抛出一个 HTTP 异常,该异常将由 异常处理器 渲染:
abort(403);您还可以提供异常的消息和应发送到浏览器的自定义 HTTP 响应头:
abort(403, 'Unauthorized.', $headers);abort_if()
abort_if 函数在给定的布尔表达式计算为 true 时抛出 HTTP 异常:
abort_if(! Auth::user()->isAdmin(), 403);与 abort 方法类似,您还可以将异常的响应文本作为第三个参数提供,并将自定义响应头数组作为第四个参数提供给函数。
abort_unless()
abort_unless 函数在给定的布尔表达式计算为 false 时抛出 HTTP 异常:
abort_unless(Auth::user()->isAdmin(), 403);与 abort 方法类似,您还可以将异常的响应文本作为第三个参数提供,并将自定义响应头数组作为第四个参数提供给函数。
app()
app 函数返回 服务容器 实例:
$container = app();您可以传递类或接口名称以从容器中解析它:
$api = app('HelpSpot\API');auth()
auth 函数返回一个 认证器 实例。您可以将其用作 Auth facade 的替代:
$user = auth()->user();如果需要,您可以指定要访问的守卫实例:
$user = auth('admin')->user();back()
back 函数生成一个 重定向 HTTP 响应 到用户的上一个位置:
return back($status = 302, $headers = [], $fallback = '/');
return back();bcrypt()
bcrypt 函数使用 Bcrypt 哈希 给定的值。您可以将此函数用作 Hash facade 的替代:
$password = bcrypt('my-secret-password');blank()
blank 函数确定给定的值是否为 "空":
blank('');
blank(' ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false有关 blank 的反义词,请参见 filled 方法。
broadcast()
broadcast(new UserRegistered($user));
broadcast(new UserRegistered($user))->toOthers();cache()
cache 函数可用于从 缓存 中获取值。如果缓存中不存在给定的键,将返回一个可选的默认值:
$value = cache('key');
$value = cache('key', 'default');您可以通过将键/值对数组传递给函数来向缓存中添加项目。您还应传递缓存值应被视为有效的秒数或持续时间:
cache(['key' => 'value'], 300);
cache(['key' => 'value'], now()->addSeconds(10));class_uses_recursive()
class_uses_recursive 函数返回一个类使用的所有 trait,包括其所有父类使用的 trait:
$traits = class_uses_recursive(App\Models\User::class);collect()
collect 函数从给定的值创建一个 集合 实例:
$collection = collect(['taylor', 'abigail']);config()
config 函数获取 配置 变量的值。配置值可以使用 "点" 语法访问,其中包括您希望访问的文件名和选项。可以指定一个默认值,如果配置选项不存在,则返回该值:
$value = config('app.timezone');
$value = config('app.timezone', $default);您可以通过传递键/值对数组在运行时设置配置变量。但是,请注意,此函数仅影响当前请求的配置值,并不会更新您的实际配置值:
config(['app.debug' => true]);cookie()
cookie 函数创建一个新的 cookie 实例:
$cookie = cookie('name', 'value', $minutes);csrf_field()
csrf_field 函数生成一个包含 CSRF 令牌值的 HTML hidden 输入字段。例如,使用 Blade 语法:
{{ csrf_field() }}csrf_token()
csrf_token 函数检索当前 CSRF 令牌的值:
$token = csrf_token();dd()
dd 函数转储给定的变量并结束脚本的执行:
dd($value);
dd($value1, $value2, $value3, ...);如果您不想在转储变量后停止脚本的执行,请使用 dump 函数。
dispatch()
dispatch 函数将给定的 作业 推送到 Laravel 作业队列:
dispatch(new App\Jobs\SendEmails);dump()
dump 函数转储给定的变量:
dump($value);
dump($value1, $value2, $value3, ...);如果您想在转储变量后停止脚本的执行,请使用 dd 函数。
env()
env 函数检索 环境变量 的值或返回默认值:
$env = env('APP_ENV');
$env = env('APP_ENV', 'production');NOTE
如果您在部署过程中执行 config:cache 命令,您应确保仅在配置文件中调用 env 函数。一旦配置被缓存,.env 文件将不会被加载,所有对 env 函数的调用将返回 null。
event()
event 函数将给定的 事件 分派给其监听器:
event(new UserRegistered($user));filled()
filled 函数确定给定的值是否不是 "空":
filled(0);
filled(true);
filled(false);
// true
filled('');
filled(' ');
filled(null);
filled(collect());
// false有关 filled 的反义词,请参见 blank 方法。
info()
info 函数将信息写入应用程序的 日志:
info('Some helpful information!');还可以将上下文数据数组传递给函数:
info('User login attempt failed.', ['id' => $user->id]);logger()
logger 函数可用于将 debug 级别的消息写入 日志:
logger('Debug message');还可以将上下文数据数组传递给函数:
logger('User has logged in.', ['id' => $user->id]);如果没有传递值给函数,将返回一个 logger 实例:
logger()->error('You are not allowed here.');method_field()
method_field 函数生成一个包含表单 HTTP 动词伪造值的 HTML hidden 输入字段。例如,使用 Blade 语法:
<form method="POST">
{{ method_field('DELETE') }}
</form>now()
now 函数为当前时间创建一个新的 Illuminate\Support\Carbon 实例:
$now = now();old()
$value = old('value');
$value = old('value', 'default');optional()
optional 函数接受任何参数,并允许您访问该对象的属性或调用方法。如果给定对象为 null,属性和方法将返回 null 而不是导致错误:
return optional($user->address)->street;
{!! old('name', optional($user)->name) !!}optional 函数还接受闭包作为其第二个参数。如果作为第一个参数提供的值不为 null,则将调用闭包:
return optional(User::find($id), function ($user) {
return $user->name;
});policy()
policy 方法检索给定类的 策略 实例:
$policy = policy(App\Models\User::class);redirect()
redirect 函数返回一个 重定向 HTTP 响应,或者如果不带参数调用,则返回重定向器实例:
return redirect($to = null, $status = 302, $headers = [], $https = null);
return redirect('/home');
return redirect()->route('route.name');report()
report 函数将使用您的 异常处理器 报告异常:
report($e);report 函数还接受字符串作为参数。当字符串传递给函数时,函数将创建一个以给定字符串为消息的异常:
report('Something went wrong.');request()
request 函数返回当前 请求 实例或从当前请求中获取输入字段的值:
$request = request();
$value = request('key', $default);rescue()
rescue 函数执行给定的闭包并捕获其执行期间发生的任何异常。所有被捕获的异常将被发送到您的 异常处理器;然而,请求将继续处理:
return rescue(function () {
return $this->method();
});您还可以将第二个参数传递给 rescue 函数。此参数将是如果在执行闭包时发生异常时应返回的 "默认" 值:
return rescue(function () {
return $this->method();
}, false);
return rescue(function () {
return $this->method();
}, function () {
return $this->failure();
});resolve()
resolve 函数使用 服务容器 将给定的类或接口名称解析为实例:
$api = resolve('HelpSpot\API');response()
response 函数创建一个 响应 实例或获取响应工厂的实例:
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);retry()
retry 函数尝试执行给定的回调,直到达到给定的最大尝试阈值。如果回调没有抛出异常,则返回其返回值。如果回调抛出异常,则会自动重试。如果超过最大尝试次数,将抛出异常:
return retry(5, function () {
// 尝试 5 次,每次尝试之间休息 100 毫秒...
}, 100);如果您希望手动计算每次尝试之间的休眠毫秒数,可以将闭包作为第三个参数传递给 retry 函数:
return retry(5, function () {
// ...
}, function ($attempt) {
return $attempt * 100;
});要仅在特定条件下重试,您可以将闭包作为第四个参数传递给 retry 函数:
return retry(5, function () {
// ...
}, 100, function ($exception) {
return $exception instanceof RetryException;
});session()
session 函数可用于获取或设置 会话 值:
$value = session('key');您可以通过将键/值对数组传递给函数来设置值:
session(['chairs' => 7, 'instruments' => 3]);如果没有传递值给函数,将返回会话存储:
$value = session()->get('key');
session()->put('key', $value);tap()
tap 函数接受两个参数:任意 $value 和一个闭包。$value 将被传递给闭包,然后由 tap 函数返回。闭包的返回值无关紧要:
$user = tap(User::first(), function ($user) {
$user->name = 'taylor';
$user->save();
});如果没有将闭包传递给 tap 函数,您可以在给定的 $value 上调用任何方法。您调用的方法的返回值将始终是 $value,无论方法在其定义中实际返回什么。例如,Eloquent update 方法通常返回一个整数。然而,我们可以通过在 tap 函数中链接 update 方法调用来强制方法返回模型本身:
$user = tap($user)->update([
'name' => $name,
'email' => $email,
]);要向类添加 tap 方法,您可以将 Illuminate\Support\Traits\Tappable trait 添加到类中。此 trait 的 tap 方法接受一个闭包作为其唯一参数。对象实例本身将被传递给闭包,然后由 tap 方法返回:
return $user->tap(function ($user) {
//
});throw_if()
throw_if 函数在给定的布尔表达式计算为 true 时抛出给定的异常:
throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);
throw_if(
! Auth::user()->isAdmin(),
AuthorizationException::class,
'You are not allowed to access this page.'
);throw_unless()
throw_unless 函数在给定的布尔表达式计算为 false 时抛出给定的异常:
throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);
throw_unless(
Auth::user()->isAdmin(),
AuthorizationException::class,
'You are not allowed to access this page.'
);today()
today 函数为当前日期创建一个新的 Illuminate\Support\Carbon 实例:
$today = today();trait_uses_recursive()
trait_uses_recursive 函数返回一个 trait 使用的所有 trait:
$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);transform()
transform 函数在给定值不是 空 时执行闭包,然后返回闭包的返回值:
$callback = function ($value) {
return $value * 2;
};
$result = transform(5, $callback);
// 10可以将默认值或闭包作为第三个参数传递给函数。如果给定值为空,则返回此值:
$result = transform(null, $callback, 'The value is blank');
// The value is blankvalidator()
validator 函数使用给定的参数创建一个新的 验证器 实例。您可以将其用作 Validator facade 的替代:
$validator = validator($data, $rules, $messages);value()
value 函数返回给定的值。然而,如果您传递一个闭包给函数,闭包将被执行并返回其返回值:
$result = value(true);
// true
$result = value(function () {
return false;
});
// falseview()
view 函数检索一个 视图 实例:
return view('auth.login');with()
with 函数返回给定的值。如果将闭包作为第二个参数传递给函数,闭包将被执行并返回其返回值:
$callback = function ($value) {
return is_numeric($value) ? $value * 2 : 0;
};
$result = with(5, $callback);
// 10
$result = with(null, $callback);
// 0
$result = with(5, null);
// 5