Helpers

Introduction

Laravel 包含各种全局“帮助”PHP 函数。其中许多功能由框架本身使用;但是,如果您觉得方便,可以在自己的应用程序中自由使用它们。

可用方法

数组和对象

Paths

Strings

流畅的弦乐

URLs

Miscellaneous

方法列表

数组和对象

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>');

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

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'