輔助函式
簡介
Laravel 提供了多種全域 PHP「輔助函式」。這些函式中,大部分都是 Laravel 本身有在使用的。不過,若你覺得這些方法很方便的話,也可以在你自己的專案內使用。
可用的方法
陣列與物件
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
路徑
字串
__ 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::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
Fluent 字串
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
URL
其他
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
方法判斷給定的值是否能以陣列方式存取:
1use Illuminate\Support\Arr;2use Illuminate\Support\Collection;34$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);56// true78$isAccessible = Arr::accessible(new Collection);910// true1112$isAccessible = Arr::accessible('abc');1314// false1516$isAccessible = Arr::accessible(new stdClass);1718// false
1use Illuminate\Support\Arr;2use Illuminate\Support\Collection;34$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);56// true78$isAccessible = Arr::accessible(new Collection);910// true1112$isAccessible = Arr::accessible('abc');1314// false1516$isAccessible = Arr::accessible(new stdClass);1718// false
Arr::add()
Arr::add
方法會在給定的索引鍵 / 值配對不存在於給定陣列、或是該索引鍵的值 null
時將該配對新增到陣列上:
1use Illuminate\Support\Arr;23$array = Arr::add(['name' => 'Desk'], 'price', 100);45// ['name' => 'Desk', 'price' => 100]67$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);89// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;23$array = Arr::add(['name' => 'Desk'], 'price', 100);45// ['name' => 'Desk', 'price' => 100]67$array = Arr::add(['name' => 'Desk', 'price' => null], 'price', 100);89// ['name' => 'Desk', 'price' => 100]
Arr::collapse()
Arr::collapse
方法將一組陣列的陣列坍縮成單一陣列:
1use Illuminate\Support\Arr;23$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);45// [1, 2, 3, 4, 5, 6, 7, 8, 9]
1use Illuminate\Support\Arr;23$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);45// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr::crossJoin()
Arr::crossJoin
方法交叉合併給定的陣列,產生一個包含所有可能排列的笛卡兒積:
1use Illuminate\Support\Arr;23$matrix = Arr::crossJoin([1, 2], ['a', 'b']);45/*6 [7 [1, 'a'],8 [1, 'b'],9 [2, 'a'],10 [2, 'b'],11 ]12*/1314$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);1516/*17 [18 [1, 'a', 'I'],19 [1, 'a', 'II'],20 [1, 'b', 'I'],21 [1, 'b', 'II'],22 [2, 'a', 'I'],23 [2, 'a', 'II'],24 [2, 'b', 'I'],25 [2, 'b', 'II'],26 ]27*/
1use Illuminate\Support\Arr;23$matrix = Arr::crossJoin([1, 2], ['a', 'b']);45/*6 [7 [1, 'a'],8 [1, 'b'],9 [2, 'a'],10 [2, 'b'],11 ]12*/1314$matrix = Arr::crossJoin([1, 2], ['a', 'b'], ['I', 'II']);1516/*17 [18 [1, 'a', 'I'],19 [1, 'a', 'II'],20 [1, 'b', 'I'],21 [1, 'b', 'II'],22 [2, 'a', 'I'],23 [2, 'a', 'II'],24 [2, 'b', 'I'],25 [2, 'b', 'II'],26 ]27*/
Arr::divide()
Arr::divide
方法回傳兩個陣列:一個陣列包含給定陣列的索引鍵,而另一個陣列則包含給定陣列的值:
1use Illuminate\Support\Arr;23[$keys, $values] = Arr::divide(['name' => 'Desk']);45// $keys: ['name']67// $values: ['Desk']
1use Illuminate\Support\Arr;23[$keys, $values] = Arr::divide(['name' => 'Desk']);45// $keys: ['name']67// $values: ['Desk']
Arr::dot()
Arr::dot
方法將多為陣列扁平化為一個使用「點 (.)」標記法來表示深度的一維陣列:
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45$flattened = Arr::dot($array);67// ['products.desk.price' => 100]
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45$flattened = Arr::dot($array);67// ['products.desk.price' => 100]
Arr::except()
Arr::except
方法從陣列中移除給定的索引鍵 / 值配對:
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100];45$filtered = Arr::except($array, ['price']);67// ['name' => 'Desk']
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100];45$filtered = Arr::except($array, ['price']);67// ['name' => 'Desk']
Arr::exists()
Arr::exists
方法會檢查給定的索引鍵是否存在於提供的陣列中:
1use Illuminate\Support\Arr;23$array = ['name' => 'John Doe', 'age' => 17];45$exists = Arr::exists($array, 'name');67// true89$exists = Arr::exists($array, 'salary');1011// false
1use Illuminate\Support\Arr;23$array = ['name' => 'John Doe', 'age' => 17];45$exists = Arr::exists($array, 'name');67// true89$exists = Arr::exists($array, 'salary');1011// false
Arr::first()
Arr::first
方法會回傳該陣列中通過給定布林測試的第一個元素:
1use Illuminate\Support\Arr;23$array = [100, 200, 300];45$first = Arr::first($array, function ($value, $key) {6 return $value >= 150;7});89// 200
1use Illuminate\Support\Arr;23$array = [100, 200, 300];45$first = Arr::first($array, function ($value, $key) {6 return $value >= 150;7});89// 200
也可以在第三個引數上提供一個預設值給該方法。若沒有任何值通過條件測試,就會回傳這個預設值:
1use Illuminate\Support\Arr;23$first = Arr::first($array, $callback, $default);
1use Illuminate\Support\Arr;23$first = Arr::first($array, $callback, $default);
Arr::flatten()
Arr::flatten
方法會將一個多維陣列扁平化為單一維度:
1use Illuminate\Support\Arr;23$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];45$flattened = Arr::flatten($array);67// ['Joe', 'PHP', 'Ruby']
1use Illuminate\Support\Arr;23$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];45$flattened = Arr::flatten($array);67// ['Joe', 'PHP', 'Ruby']
Arr::forget()
Arr::forget
方法使用「點 (.)」標記法來在多層巢狀陣列中移除給定的索引鍵 / 值配對:
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45Arr::forget($array, 'products.desk');67// ['products' => []]
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45Arr::forget($array, 'products.desk');67// ['products' => []]
Arr::get()
Arr::get
方法使用「點 (.)」標記法來在多層巢狀陣列中取值:
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45$price = Arr::get($array, 'products.desk.price');67// 100
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45$price = Arr::get($array, 'products.desk.price');67// 100
Arr::get
還接受一個預設值。若指定的索引鍵不存在時會回傳該預設值:
1use Illuminate\Support\Arr;23$discount = Arr::get($array, 'products.desk.discount', 0);45// 0
1use Illuminate\Support\Arr;23$discount = Arr::get($array, 'products.desk.discount', 0);45// 0
Arr::has()
Arr::has
方法使用「點 (.)」標記法來檢查給定的一個或多個項目是否存在:
1use Illuminate\Support\Arr;23$array = ['product' => ['name' => 'Desk', 'price' => 100]];45$contains = Arr::has($array, 'product.name');67// true89$contains = Arr::has($array, ['product.price', 'product.discount']);1011// false
1use Illuminate\Support\Arr;23$array = ['product' => ['name' => 'Desk', 'price' => 100]];45$contains = Arr::has($array, 'product.name');67// true89$contains = Arr::has($array, ['product.price', 'product.discount']);1011// false
Arr::hasAny()
Arr::hasAny
方法使用「點 (.)」標記法來檢查給定的多個項目中是否只少有一個存在:
1use Illuminate\Support\Arr;23$array = ['product' => ['name' => 'Desk', 'price' => 100]];45$contains = Arr::hasAny($array, 'product.name');67// true89$contains = Arr::hasAny($array, ['product.name', 'product.discount']);1011// true1213$contains = Arr::hasAny($array, ['category', 'product.discount']);1415// false
1use Illuminate\Support\Arr;23$array = ['product' => ['name' => 'Desk', 'price' => 100]];45$contains = Arr::hasAny($array, 'product.name');67// true89$contains = Arr::hasAny($array, ['product.name', 'product.discount']);1011// true1213$contains = Arr::hasAny($array, ['category', 'product.discount']);1415// false
Arr::isAssoc()
若給定的陣列為關聯式陣列,Arr::isAssoc
方法會回傳 true
。當某個陣列的索引鍵不是以 0 開始依序排列的數字時,就是「關聯式」的陣列:
1use Illuminate\Support\Arr;23$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);45// true67$isAssoc = Arr::isAssoc([1, 2, 3]);89// false
1use Illuminate\Support\Arr;23$isAssoc = Arr::isAssoc(['product' => ['name' => 'Desk', 'price' => 100]]);45// true67$isAssoc = Arr::isAssoc([1, 2, 3]);89// false
Arr::isList()
若給定陣列的索引鍵是從 0 開始的有序整數的話,Arr::isList
方法會回傳 true
:
1use Illuminate\Support\Arr;23$isList = Arr::isList(['foo', 'bar', 'baz']);45// true67$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);89// false
1use Illuminate\Support\Arr;23$isList = Arr::isList(['foo', 'bar', 'baz']);45// true67$isList = Arr::isList(['product' => ['name' => 'Desk', 'price' => 100]]);89// false
Arr::join()
Arr::join
方法可使用字串來將各個陣列元素串接在一起。也可以用該方法的第二個引數來指定用於串接陣列中最後一個元素的字串:
1use Illuminate\Support\Arr;23$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];45$joined = Arr::join($array, ', ');67// Tailwind, Alpine, Laravel, Livewire89$joined = Arr::join($array, ', ', ' and ');1011// Tailwind, Alpine, Laravel and Livewire
1use Illuminate\Support\Arr;23$array = ['Tailwind', 'Alpine', 'Laravel', 'Livewire'];45$joined = Arr::join($array, ', ');67// Tailwind, Alpine, Laravel, Livewire89$joined = Arr::join($array, ', ', ' and ');1011// Tailwind, Alpine, Laravel and Livewire
Arr::keyBy()
Arr::keyBy
方法依照給定的索引鍵來為該陣列加上索引鍵。若多個項目有相同的索引鍵,則新的陣列中只會包含最後一個項目:
1use Illuminate\Support\Arr;23$array = [4 ['product_id' => 'prod-100', 'name' => 'Desk'],5 ['product_id' => 'prod-200', 'name' => 'Chair'],6];78$keyed = Arr::keyBy($array, 'product_id');910/*11 [12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],14 ]15*/
1use Illuminate\Support\Arr;23$array = [4 ['product_id' => 'prod-100', 'name' => 'Desk'],5 ['product_id' => 'prod-200', 'name' => 'Chair'],6];78$keyed = Arr::keyBy($array, 'product_id');910/*11 [12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],14 ]15*/
Arr::last()
Arr::last
方法會回傳該陣列中通過給定布林測試的最後一個元素:
1use Illuminate\Support\Arr;23$array = [100, 200, 300, 110];45$last = Arr::last($array, function ($value, $key) {6 return $value >= 150;7});89// 300
1use Illuminate\Support\Arr;23$array = [100, 200, 300, 110];45$last = Arr::last($array, function ($value, $key) {6 return $value >= 150;7});89// 300
可以在第三個引數上提供一個預設值給該方法。若沒有任何值通過條件測試,就會回傳這個預設值:
1use Illuminate\Support\Arr;23$last = Arr::last($array, $callback, $default);
1use Illuminate\Support\Arr;23$last = Arr::last($array, $callback, $default);
Arr::map()
Arr::map
可用於迭代整個陣列,並將各個陣列值與索引鍵傳入給定的回呼中。陣列值會被回呼中回傳的值給取代:
1use Illuminate\Support\Arr;23$array = ['first' => 'james', 'last' => 'kirk'];45$mapped = Arr::map($array, function ($value, $key) {6 return ucfirst($value);7});89// ['first' => 'James', 'last' => 'Kirk']
1use Illuminate\Support\Arr;23$array = ['first' => 'james', 'last' => 'kirk'];45$mapped = Arr::map($array, function ($value, $key) {6 return ucfirst($value);7});89// ['first' => 'James', 'last' => 'Kirk']
Arr::only()
Arr::only
方法回傳給定陣列中特定的索引鍵 / 值配對:
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];45$slice = Arr::only($array, ['name', 'price']);67// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];45$slice = Arr::only($array, ['name', 'price']);67// ['name' => 'Desk', 'price' => 100]
Arr::pluck()
Arr::pluck
方法可從給定陣列中取得給定索引鍵內的所有值:
1use Illuminate\Support\Arr;23$array = [4 ['developer' => ['id' => 1, 'name' => 'Taylor']],5 ['developer' => ['id' => 2, 'name' => 'Abigail']],6];78$names = Arr::pluck($array, 'developer.name');910// ['Taylor', 'Abigail']
1use Illuminate\Support\Arr;23$array = [4 ['developer' => ['id' => 1, 'name' => 'Taylor']],5 ['developer' => ['id' => 2, 'name' => 'Abigail']],6];78$names = Arr::pluck($array, 'developer.name');910// ['Taylor', 'Abigail']
也可以指定產生的清單要如何設定索引鍵:
1use Illuminate\Support\Arr;23$names = Arr::pluck($array, 'developer.name', 'developer.id');45// [1 => 'Taylor', 2 => 'Abigail']
1use Illuminate\Support\Arr;23$names = Arr::pluck($array, 'developer.name', 'developer.id');45// [1 => 'Taylor', 2 => 'Abigail']
Arr::prepend()
Arr::prepend
方法會將某個項目放到該陣列的最前面:
1use Illuminate\Support\Arr;23$array = ['one', 'two', 'three', 'four'];45$array = Arr::prepend($array, 'zero');67// ['zero', 'one', 'two', 'three', 'four']
1use Illuminate\Support\Arr;23$array = ['one', 'two', 'three', 'four'];45$array = Arr::prepend($array, 'zero');67// ['zero', 'one', 'two', 'three', 'four']
若有需要,也可以指定該值要使用的索引鍵:
1use Illuminate\Support\Arr;23$array = ['price' => 100];45$array = Arr::prepend($array, 'Desk', 'name');67// ['name' => 'Desk', 'price' => 100]
1use Illuminate\Support\Arr;23$array = ['price' => 100];45$array = Arr::prepend($array, 'Desk', 'name');67// ['name' => 'Desk', 'price' => 100]
Arr::prependKeysWith()
Arr::prependKeysWith
會將關聯式陣列中,將所有的索引鍵名稱加上給定的前置詞:
1use Illuminate\Support\Arr;23$array = [4 'name' => 'Desk',5 'price' => 100,6];78$keyed = Arr::prependKeysWith($array, 'product.');910/*11 [12 'product.name' => 'Desk',13 'product.price' => 100,14 ]15*/
1use Illuminate\Support\Arr;23$array = [4 'name' => 'Desk',5 'price' => 100,6];78$keyed = Arr::prependKeysWith($array, 'product.');910/*11 [12 'product.name' => 'Desk',13 'product.price' => 100,14 ]15*/
Arr::pull()
Arr::pull
方法從陣列中移除一組索引鍵 / 值配對:
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100];45$name = Arr::pull($array, 'name');67// $name: Desk89// $array: ['price' => 100]
1use Illuminate\Support\Arr;23$array = ['name' => 'Desk', 'price' => 100];45$name = Arr::pull($array, 'name');67// $name: Desk89// $array: ['price' => 100]
可以在第三個引數上提供一個預設值給該方法。若指定的索引鍵不存在,就會回傳這個預設值:
1use Illuminate\Support\Arr;23$value = Arr::pull($array, $key, $default);
1use Illuminate\Support\Arr;23$value = Arr::pull($array, $key, $default);
Arr::query()
Arr::query
方法將該陣列轉換為查詢字串:
1use Illuminate\Support\Arr;23$array = [4 'name' => 'Taylor',5 'order' => [6 'column' => 'created_at',7 'direction' => 'desc'8 ]9];1011Arr::query($array);1213// name=Taylor&order[column]=created_at&order[direction]=desc
1use Illuminate\Support\Arr;23$array = [4 'name' => 'Taylor',5 'order' => [6 'column' => 'created_at',7 'direction' => 'desc'8 ]9];1011Arr::query($array);1213// name=Taylor&order[column]=created_at&order[direction]=desc
Arr::random()
Arr::random
方法從陣列中隨機回傳一個值:
1use Illuminate\Support\Arr;23$array = [1, 2, 3, 4, 5];45$random = Arr::random($array);67// 4 - (retrieved randomly)
1use Illuminate\Support\Arr;23$array = [1, 2, 3, 4, 5];45$random = Arr::random($array);67// 4 - (retrieved randomly)
也可以在第二個引數上指定要回傳項目的數量。請注意,若有提供第二個引數,就算只要求一個項目,還是會回傳一組陣列:
1use Illuminate\Support\Arr;23$items = Arr::random($array, 2);45// [2, 5] - (retrieved randomly)
1use Illuminate\Support\Arr;23$items = Arr::random($array, 2);45// [2, 5] - (retrieved randomly)
Arr::set()
Arr::set
方法可使用「點 (.)」標記法來在多層巢狀陣列中賦值:
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45Arr::set($array, 'products.desk.price', 200);67// ['products' => ['desk' => ['price' => 200]]]
1use Illuminate\Support\Arr;23$array = ['products' => ['desk' => ['price' => 100]]];45Arr::set($array, 'products.desk.price', 200);67// ['products' => ['desk' => ['price' => 200]]]
Arr::shuffle()
Arr::shuffle
方法會隨機排序該陣列內的項目:
1use Illuminate\Support\Arr;23$array = Arr::shuffle([1, 2, 3, 4, 5]);45// [3, 2, 5, 1, 4] - (generated randomly)
1use Illuminate\Support\Arr;23$array = Arr::shuffle([1, 2, 3, 4, 5]);45// [3, 2, 5, 1, 4] - (generated randomly)
Arr::sort()
Arr::sort
方法以陣列內的值來排列陣列:
1use Illuminate\Support\Arr;23$array = ['Desk', 'Table', 'Chair'];45$sorted = Arr::sort($array);67// ['Chair', 'Desk', 'Table']
1use Illuminate\Support\Arr;23$array = ['Desk', 'Table', 'Chair'];45$sorted = Arr::sort($array);67// ['Chair', 'Desk', 'Table']
也可以使用給定閉包的執行結果來排序陣列:
1use Illuminate\Support\Arr;23$array = [4 ['name' => 'Desk'],5 ['name' => 'Table'],6 ['name' => 'Chair'],7];89$sorted = array_values(Arr::sort($array, function ($value) {10 return $value['name'];11}));1213/*14 [15 ['name' => 'Chair'],16 ['name' => 'Desk'],17 ['name' => 'Table'],18 ]19*/
1use Illuminate\Support\Arr;23$array = [4 ['name' => 'Desk'],5 ['name' => 'Table'],6 ['name' => 'Chair'],7];89$sorted = array_values(Arr::sort($array, function ($value) {10 return $value['name'];11}));1213/*14 [15 ['name' => 'Chair'],16 ['name' => 'Desk'],17 ['name' => 'Table'],18 ]19*/
Arr::sortDesc()
Arr::sortDesc
方法將陣列以其值來降冪排序:
1use Illuminate\Support\Arr;23$array = ['Desk', 'Table', 'Chair'];45$sorted = Arr::sortDesc($array);67// ['Table', 'Desk', 'Chair']
1use Illuminate\Support\Arr;23$array = ['Desk', 'Table', 'Chair'];45$sorted = Arr::sortDesc($array);67// ['Table', 'Desk', 'Chair']
也可以使用給定閉包的執行結果來排序陣列:
1use Illuminate\Support\Arr;23$array = [4 ['name' => 'Desk'],5 ['name' => 'Table'],6 ['name' => 'Chair'],7];89$sorted = array_values(Arr::sortDesc($array, function ($value) {10 return $value['name'];11}));1213/*14 [15 ['name' => 'Table'],16 ['name' => 'Desk'],17 ['name' => 'Chair'],18 ]19*/
1use Illuminate\Support\Arr;23$array = [4 ['name' => 'Desk'],5 ['name' => 'Table'],6 ['name' => 'Chair'],7];89$sorted = array_values(Arr::sortDesc($array, function ($value) {10 return $value['name'];11}));1213/*14 [15 ['name' => 'Table'],16 ['name' => 'Desk'],17 ['name' => 'Chair'],18 ]19*/
Arr::sortRecursive()
Arr::sortRecursive
方法會遞迴排序陣列。當遇到數字索引鍵的子陣列時,會使用 sort
函式;若子陣列為關聯式陣列,則使用 ksort
函式:
1use Illuminate\Support\Arr;23$array = [4 ['Roman', 'Taylor', 'Li'],5 ['PHP', 'Ruby', 'JavaScript'],6 ['one' => 1, 'two' => 2, 'three' => 3],7];89$sorted = Arr::sortRecursive($array);1011/*12 [13 ['JavaScript', 'PHP', 'Ruby'],14 ['one' => 1, 'three' => 3, 'two' => 2],15 ['Li', 'Roman', 'Taylor'],16 ]17*/
1use Illuminate\Support\Arr;23$array = [4 ['Roman', 'Taylor', 'Li'],5 ['PHP', 'Ruby', 'JavaScript'],6 ['one' => 1, 'two' => 2, 'three' => 3],7];89$sorted = Arr::sortRecursive($array);1011/*12 [13 ['JavaScript', 'PHP', 'Ruby'],14 ['one' => 1, 'three' => 3, 'two' => 2],15 ['Li', 'Roman', 'Taylor'],16 ]17*/
Arr::toCssClasses()
Arr::toCssClasses
可以有條件地編譯 CSS class 字串。該方法接受一組包含 class 的陣列,其中,陣列的索引鍵代表欲新增的 class,陣列值則是一個布林運算式。若陣列的元素有數字索引鍵,則該元素一定會被加到轉譯後的 Class 列表上:
1use Illuminate\Support\Arr;23$isActive = false;4$hasError = true;56$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];78$classes = Arr::toCssClasses($array);910/*11 'p-4 bg-red'12*/
1use Illuminate\Support\Arr;23$isActive = false;4$hasError = true;56$array = ['p-4', 'font-bold' => $isActive, 'bg-red' => $hasError];78$classes = Arr::toCssClasses($array);910/*11 'p-4 bg-red'12*/
該方法用於提供了 Laravel 的「將 Class 於 Blade 元件的 Attribute Bag 合併」功能,以及 @class
Blade 指示詞。
Arr::undot()
Arr::undot
方法將一組使用「點 (.)」標記法的一維陣列展開為多維陣列:
1use Illuminate\Support\Arr;23$array = [4 'user.name' => 'Kevin Malone',5 'user.occupation' => 'Accountant',6];78$array = Arr::undot($array);910// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
1use Illuminate\Support\Arr;23$array = [4 'user.name' => 'Kevin Malone',5 'user.occupation' => 'Accountant',6];78$array = Arr::undot($array);910// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
Arr::where()
Arr::where
方法使用給定的閉包來篩選陣列:
1use Illuminate\Support\Arr;23$array = [100, '200', 300, '400', 500];45$filtered = Arr::where($array, function ($value, $key) {6 return is_string($value);7});89// [1 => '200', 3 => '400']
1use Illuminate\Support\Arr;23$array = [100, '200', 300, '400', 500];45$filtered = Arr::where($array, function ($value, $key) {6 return is_string($value);7});89// [1 => '200', 3 => '400']
Arr::whereNotNull()
Arr::whereNotNull
方法從給定陣列中移除所有 null
的值:
1use Illuminate\Support\Arr;23$array = [0, null];45$filtered = Arr::whereNotNull($array);67// [0 => 0]
1use Illuminate\Support\Arr;23$array = [0, null];45$filtered = Arr::whereNotNull($array);67// [0 => 0]
Arr::wrap()
Arr::wrap
將給定值包裝為陣列。若給定的值已為陣列,則該方法會直接回傳該陣列,不做其他修改:
1use Illuminate\Support\Arr;23$string = 'Laravel';45$array = Arr::wrap($string);67// ['Laravel']
1use Illuminate\Support\Arr;23$string = 'Laravel';45$array = Arr::wrap($string);67// ['Laravel']
若給定值為 null
,則會回傳空陣列:
1use Illuminate\Support\Arr;23$array = Arr::wrap(null);45// []
1use Illuminate\Support\Arr;23$array = Arr::wrap(null);45// []
data_fill()
data_fill
方法使用「點 (.)」標記法來在巢狀陣列或物件中填上原本不存在的值:
1$data = ['products' => ['desk' => ['price' => 100]]];23data_fill($data, 'products.desk.price', 200);45// ['products' => ['desk' => ['price' => 100]]]67data_fill($data, 'products.desk.discount', 10);89// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
1$data = ['products' => ['desk' => ['price' => 100]]];23data_fill($data, 'products.desk.price', 200);45// ['products' => ['desk' => ['price' => 100]]]67data_fill($data, 'products.desk.discount', 10);89// ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
該方法也支援使用星號作為萬用字元,會填上對應的目標:
1$data = [2 'products' => [3 ['name' => 'Desk 1', 'price' => 100],4 ['name' => 'Desk 2'],5 ],6];78data_fill($data, 'products.*.price', 200);910/*11 [12 'products' => [13 ['name' => 'Desk 1', 'price' => 100],14 ['name' => 'Desk 2', 'price' => 200],15 ],16 ]17*/
1$data = [2 'products' => [3 ['name' => 'Desk 1', 'price' => 100],4 ['name' => 'Desk 2'],5 ],6];78data_fill($data, 'products.*.price', 200);910/*11 [12 'products' => [13 ['name' => 'Desk 1', 'price' => 100],14 ['name' => 'Desk 2', 'price' => 200],15 ],16 ]17*/
data_get()
data_get
方法使用「點 (.)」標記法來從巢狀陣列或物件中取值:
1$data = ['products' => ['desk' => ['price' => 100]]];23$price = data_get($data, 'products.desk.price');45// 100
1$data = ['products' => ['desk' => ['price' => 100]]];23$price = data_get($data, 'products.desk.price');45// 100
data_get
還接受一個預設值。若找不到指定的索引鍵時會回傳該預設值:
1$discount = data_get($data, 'products.desk.discount', 0);23// 0
1$discount = data_get($data, 'products.desk.discount', 0);23// 0
該方法也接受使用星號來作為萬用字元,可以套用到陣列或物件上的任何索引鍵:
1$data = [2 'product-one' => ['name' => 'Desk 1', 'price' => 100],3 'product-two' => ['name' => 'Desk 2', 'price' => 150],4];56data_get($data, '*.name');78// ['Desk 1', 'Desk 2'];
1$data = [2 'product-one' => ['name' => 'Desk 1', 'price' => 100],3 'product-two' => ['name' => 'Desk 2', 'price' => 150],4];56data_get($data, '*.name');78// ['Desk 1', 'Desk 2'];
data_set()
data_set
函式使用「點 (.)」標記法來在巢狀陣列或物件上賦值:
1$data = ['products' => ['desk' => ['price' => 100]]];23data_set($data, 'products.desk.price', 200);45// ['products' => ['desk' => ['price' => 200]]]
1$data = ['products' => ['desk' => ['price' => 100]]];23data_set($data, 'products.desk.price', 200);45// ['products' => ['desk' => ['price' => 200]]]
該函式也接受使用星號作為萬用字元,會為設定相應的目標賦值:
1$data = [2 'products' => [3 ['name' => 'Desk 1', 'price' => 100],4 ['name' => 'Desk 2', 'price' => 150],5 ],6];78data_set($data, 'products.*.price', 200);910/*11 [12 'products' => [13 ['name' => 'Desk 1', 'price' => 200],14 ['name' => 'Desk 2', 'price' => 200],15 ],16 ]17*/
1$data = [2 'products' => [3 ['name' => 'Desk 1', 'price' => 100],4 ['name' => 'Desk 2', 'price' => 150],5 ],6];78data_set($data, 'products.*.price', 200);910/*11 [12 'products' => [13 ['name' => 'Desk 1', 'price' => 200],14 ['name' => 'Desk 2', 'price' => 200],15 ],16 ]17*/
預設情況下,會複寫現有的值。若只想為不存在的項目賦值,可傳入 false
作為第四個引數給該函式:
1$data = ['products' => ['desk' => ['price' => 100]]];23data_set($data, 'products.desk.price', 200, overwrite: false);45// ['products' => ['desk' => ['price' => 100]]]
1$data = ['products' => ['desk' => ['price' => 100]]];23data_set($data, 'products.desk.price', 200, overwrite: false);45// ['products' => ['desk' => ['price' => 100]]]
head()
head
方法回傳給定陣列中的第一個元素:
1$array = [100, 200, 300];23$first = head($array);45// 100
1$array = [100, 200, 300];23$first = head($array);45// 100
last()
last
方法回傳給定陣列中的最後一個元素:
1$array = [100, 200, 300];23$last = last($array);45// 300
1$array = [100, 200, 300];23$last = last($array);45// 300
路徑
app_path()
app_path
回傳專案 app
目錄的完整名稱路徑。也可以使用 app_path
函式來為 app 目錄下相對路徑的完整名稱路徑:
1$path = app_path();23$path = app_path('Http/Controllers/Controller.php');
1$path = app_path();23$path = app_path('Http/Controllers/Controller.php');
base_path()
base_path
函式回傳專案根目錄的完整名稱路徑。也可以使用 base_path
來產生相對於根目錄下給定檔案的完整名稱路徑:
1$path = base_path();23$path = base_path('vendor/bin');
1$path = base_path();23$path = base_path('vendor/bin');
config_path()
config_path
函式回傳專案 config
目錄的完整名稱路徑。也可以使用 config_path
函式來產生專案 config
目錄內給定檔案的完整名稱路徑:
1$path = config_path();23$path = config_path('app.php');
1$path = config_path();23$path = config_path('app.php');
database_path()
database_path
函式回傳專案 database
目錄的完整名稱路徑。也可以使用 database_path
函式來產生 database
目錄下給定檔案的完整名稱路徑:
1$path = database_path();23$path = database_path('factories/UserFactory.php');
1$path = database_path();23$path = database_path('factories/UserFactory.php');
lang_path()
lang_path
函式回傳專案 lang
目錄的完整名稱路徑。也可以使用 lang_path
函式來產生 lang
目錄下給定檔案的完整名稱路徑:
1$path = lang_path();23$path = lang_path('en/messages.php');
1$path = lang_path();23$path = lang_path('en/messages.php');
mix()
mix
函式回傳版本化的 Mix 檔案路徑:
1$path = mix('css/app.css');
1$path = mix('css/app.css');
public_path()
public_path
函式回傳專案 public
目錄的完整名稱路徑。也可以使用 public_path
函式來產生 public
目錄下給定檔案的完整名稱路徑:
1$path = public_path();23$path = public_path('css/app.css');
1$path = public_path();23$path = public_path('css/app.css');
resource_path()
resource_path
函式回傳專案 resources
目錄的完整名稱路徑。也可以使用 resource_path
函式來產生 resources
目錄下給定檔案的完整名稱路徑:
1$path = resource_path();23$path = resource_path('sass/app.scss');
1$path = resource_path();23$path = resource_path('sass/app.scss');
storage_path()
storage_path
函式回傳專案 storage
目錄的完整名稱路徑。也可以使用 storage_path
函式來產生 storage
目錄下給定檔案的完整名稱路徑:
1$path = storage_path();23$path = storage_path('app/file.txt');
1$path = storage_path();23$path = storage_path('app/file.txt');
字串
__()
__
函式使用語系檔來翻譯給定的翻譯字串或翻譯索引鍵:
1echo __('Welcome to our application');23echo __('messages.welcome');
1echo __('Welcome to our application');23echo __('messages.welcome');
若指定的翻譯字串或翻譯索引鍵不存在時,__
函式會回傳給定的值。因此,在上述範例中,若 messages.welcome
索引鍵不存在,__
函式會回傳 messages.welcome
。
class_basename()
class_basename
函式回傳給定類別在移除類別 Namespace 後的類別名稱:
1$class = class_basename('Foo\Bar\Baz');23// Baz
1$class = class_basename('Foo\Bar\Baz');23// Baz
e()
e
函式執行 PHP 的 htmlspecialchars
函式,其中 double_encode
選項預設為 true
:
1echo e('<html>foo</html>');23// <html>foo</html>
1echo e('<html>foo</html>');23// <html>foo</html>
preg_replace_array()
preg_replace_array
函式使用陣列來依序在陣列中取代給定的格式:
1$string = 'The event will take place between :start and :end';23$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);45// The event will take place between 8:30 and 9:00
1$string = 'The event will take place between :start and :end';23$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);45// The event will take place between 8:30 and 9:00
Str::after()
Str::after
方法回傳字串中給定值以後的所有內容。若該字串中找不到給定值,會回傳整個字串:
1use Illuminate\Support\Str;23$slice = Str::after('This is my name', 'This is');45// ' my name'
1use Illuminate\Support\Str;23$slice = Str::after('This is my name', 'This is');45// ' my name'
Str::afterLast()
Str::afterLast
方法回傳給定字串後最後一個出現給定值之後的所有內容。若找不到該值,會回傳整個字串:
1use Illuminate\Support\Str;23$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');45// 'Controller'
1use Illuminate\Support\Str;23$slice = Str::afterLast('App\Http\Controllers\Controller', '\\');45// 'Controller'
Str::ascii()
Str::ascii
方法會嘗試將給定字串翻譯為 ASCII 值:
1use Illuminate\Support\Str;23$slice = Str::ascii('û');45// 'u'
1use Illuminate\Support\Str;23$slice = Str::ascii('û');45// 'u'
Str::before()
Str::before
回傳字串在遇到給定值前的所有內容:
1use Illuminate\Support\Str;23$slice = Str::before('This is my name', 'my name');45// 'This is '
1use Illuminate\Support\Str;23$slice = Str::before('This is my name', 'my name');45// 'This is '
Str::beforeLast()
Str::beforeLast
方法回傳字串中最後一次出現給定值以前的所有內容:
1use Illuminate\Support\Str;23$slice = Str::beforeLast('This is my name', 'is');45// 'This '
1use Illuminate\Support\Str;23$slice = Str::beforeLast('This is my name', 'is');45// 'This '
Str::between()
Str::between
方法回傳介於兩個值之間的字串:
1use Illuminate\Support\Str;23$slice = Str::between('This is my name', 'This', 'name');45// ' is my '
1use Illuminate\Support\Str;23$slice = Str::between('This is my name', 'This', 'name');45// ' is my '
Str::betweenFirst()
Str::betweenFirst
方法回傳介於兩個值之間,最小的可能字串部分:
1use Illuminate\Support\Str;23$slice = Str::betweenFirst('[a] bc [d]', '[', ']');45// 'a'
1use Illuminate\Support\Str;23$slice = Str::betweenFirst('[a] bc [d]', '[', ']');45// 'a'
Str::camel()
Str::camel
方法將給定字串轉為 camelCase
—— 駝峰命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::camel('foo_bar');45// fooBar
1use Illuminate\Support\Str;23$converted = Str::camel('foo_bar');45// fooBar
Str::contains()
Str::contains
方法判斷給定字串是否包含給定值。該方法區分大小寫:
1use Illuminate\Support\Str;23$contains = Str::contains('This is my name', 'my');45// true
1use Illuminate\Support\Str;23$contains = Str::contains('This is my name', 'my');45// true
也可以傳入一組要判斷的陣列值,來判斷給定字串中是否有包含該陣列中任何一個值:
1use Illuminate\Support\Str;23$contains = Str::contains('This is my name', ['my', 'foo']);45// true
1use Illuminate\Support\Str;23$contains = Str::contains('This is my name', ['my', 'foo']);45// true
Str::containsAll()
Str::containsAll
判斷給定字串是否有包含給定陣列中的所有值:
1use Illuminate\Support\Str;23$containsAll = Str::containsAll('This is my name', ['my', 'name']);45// true
1use Illuminate\Support\Str;23$containsAll = Str::containsAll('This is my name', ['my', 'name']);45// true
Str::endsWith()
Str::endsWith` 方法可判斷給定字串是否以給定值結尾:
1use Illuminate\Support\Str;23$result = Str::endsWith('This is my name', 'name');45// true
1use Illuminate\Support\Str;23$result = Str::endsWith('This is my name', 'name');45// true
也可以傳入一組陣列值來判斷給定字串的結尾是否符合該陣列內的其中一項:
1use Illuminate\Support\Str;23$result = Str::endsWith('This is my name', ['name', 'foo']);45// true67$result = Str::endsWith('This is my name', ['this', 'foo']);89// false
1use Illuminate\Support\Str;23$result = Str::endsWith('This is my name', ['name', 'foo']);45// true67$result = Str::endsWith('This is my name', ['this', 'foo']);89// false
Str::excerpt()
Str::excerpt
方法從給定字串中截取摘要,這個摘要符合該字串中第一個符合給定片語 (Phrase) 的實體:
1use Illuminate\Support\Str;23$excerpt = Str::excerpt('This is my name', 'my', [4 'radius' => 35]);67// '...is my na...'
1use Illuminate\Support\Str;23$excerpt = Str::excerpt('This is my name', 'my', [4 'radius' => 35]);67// '...is my na...'
radius
選項的預設值為 100
。該選項可用來定義經過截取的字串中左右兩邊各需顯式多少個字元:
此外,也可使用 omission
選項來定義應被加到截取字串前後的字串:
1use Illuminate\Support\Str;23$excerpt = Str::excerpt('This is my name', 'name', [4 'radius' => 3,5 'omission' => '(...) '6]);78// '(...) my name'
1use Illuminate\Support\Str;23$excerpt = Str::excerpt('This is my name', 'name', [4 'radius' => 3,5 'omission' => '(...) '6]);78// '(...) my name'
Str::finish()
Str::finish
方法會在給定字串不是以給定值結尾時,在該字串後方加上這個值:
1use Illuminate\Support\Str;23$adjusted = Str::finish('this/string', '/');45// this/string/67$adjusted = Str::finish('this/string/', '/');89// this/string/
1use Illuminate\Support\Str;23$adjusted = Str::finish('this/string', '/');45// this/string/67$adjusted = Str::finish('this/string/', '/');89// this/string/
Str::headline()
Str::headline
方法將以大小寫、減號、底線等方式區隔的字串轉換為以空格區隔的字串,並將其中每個單詞的首字母都轉為大寫:
1use Illuminate\Support\Str;23$headline = Str::headline('steve_jobs');45// Steve Jobs67$headline = Str::headline('EmailNotificationSent');89// Email Notification Sent
1use Illuminate\Support\Str;23$headline = Str::headline('steve_jobs');45// Steve Jobs67$headline = Str::headline('EmailNotificationSent');89// Email Notification Sent
Str::inlineMarkdown()
Str::inlineMarkdown
方法使用 CommonMarkdown 來將 GitHub Flavored Markdown 轉換為內嵌的 HTML。不過,與 markdown
不同,該方法不會將所有產生的 HTML 以區塊層級的元素包裝起來。
1use Illuminate\Support\Str;23$html = Str::inlineMarkdown('**Laravel**');45// <strong>Laravel</strong>
1use Illuminate\Support\Str;23$html = Str::inlineMarkdown('**Laravel**');45// <strong>Laravel</strong>
Str::is()
Str::is
判斷給定字串是否符合給定的格式。可使用星號作為萬用字元:
1use Illuminate\Support\Str;23$matches = Str::is('foo*', 'foobar');45// true67$matches = Str::is('baz*', 'foobar');89// false
1use Illuminate\Support\Str;23$matches = Str::is('foo*', 'foobar');45// true67$matches = Str::is('baz*', 'foobar');89// false
Str::isAscii()
Str::isAscii
方法判斷給定字串是否為 7 位元 ASCII:
1use Illuminate\Support\Str;23$isAscii = Str::isAscii('Taylor');45// true67$isAscii = Str::isAscii('ü');89// false
1use Illuminate\Support\Str;23$isAscii = Str::isAscii('Taylor');45// true67$isAscii = Str::isAscii('ü');89// false
Str::isJson()
Str::isJson
方法會判斷給定字串是否為有效的 JSON:
1use Illuminate\Support\Str;23$result = Str::isJson('[1,2,3]');45// true67$result = Str::isJson('{"first": "John", "last": "Doe"}');89// true1011$result = Str::isJson('{first: "John", last: "Doe"}');1213// false
1use Illuminate\Support\Str;23$result = Str::isJson('[1,2,3]');45// true67$result = Str::isJson('{"first": "John", "last": "Doe"}');89// true1011$result = Str::isJson('{first: "John", last: "Doe"}');1213// false
Str::isUlid()
Str::isUlid
方法可判斷給定字串是否為有效的 ULID:
1use Illuminate\Support\Str;23$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');45// true67$isUlid = Str::isUlid('laravel');89// false
1use Illuminate\Support\Str;23$isUlid = Str::isUlid('01gd6r360bp37zj17nxb55yv40');45// true67$isUlid = Str::isUlid('laravel');89// false
Str::isUuid()
Str::isUuid
方法判斷給定字串是否為有效的 UUID:
1use Illuminate\Support\Str;23$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');45// true67$isUuid = Str::isUuid('laravel');89// false
1use Illuminate\Support\Str;23$isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de');45// true67$isUuid = Str::isUuid('laravel');89// false
Str::kebab()
Str::kebab
方法將給定字串轉換為 kebab-case
:
1use Illuminate\Support\Str;23$converted = Str::kebab('fooBar');45// foo-bar
1use Illuminate\Support\Str;23$converted = Str::kebab('fooBar');45// foo-bar
Str::lcfirst()
Str::lcfirst
方法回傳給定字串第一個字元轉為小寫後的字串:
1use Illuminate\Support\Str;23$string = Str::lcfirst('Foo Bar');45// foo Bar
1use Illuminate\Support\Str;23$string = Str::lcfirst('Foo Bar');45// foo Bar
Str::length()
Str::length
方法回傳給定字串的長度:
1use Illuminate\Support\Str;23$length = Str::length('Laravel');45// 7
1use Illuminate\Support\Str;23$length = Str::length('Laravel');45// 7
Str::limit()
Str::limit
方法將給定字串截斷成指定長度:
1use Illuminate\Support\Str;23$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);45// The quick brown fox...
1use Illuminate\Support\Str;23$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20);45// The quick brown fox...
也可以傳入第三個引數給該方法,以更改當字串被截斷時要加在最後方的內容:
1use Illuminate\Support\Str;23$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');45// The quick brown fox (...)
1use Illuminate\Support\Str;23$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');45// The quick brown fox (...)
Str::lower()
Str::lower
方法將給定字串轉為小寫:
1use Illuminate\Support\Str;23$converted = Str::lower('LARAVEL');45// laravel
1use Illuminate\Support\Str;23$converted = Str::lower('LARAVEL');45// laravel
Str::markdown()
Str::markdown
方法使用 CommonMark 來將 GitHub Flavored Markdown 轉換為 HTML:
1use Illuminate\Support\Str;23$html = Str::markdown('# Laravel');45// <h1>Laravel</h1>67$html = Str::markdown('# Taylor <b>Otwell</b>', [8 'html_input' => 'strip',9]);1011// <h1>Taylor Otwell</h1>
1use Illuminate\Support\Str;23$html = Str::markdown('# Laravel');45// <h1>Laravel</h1>67$html = Str::markdown('# Taylor <b>Otwell</b>', [8 'html_input' => 'strip',9]);1011// <h1>Taylor Otwell</h1>
Str::mask()
Str::mask
方法將字串中的一部分轉為重複字元,可用來為 E-Mail 位址或電話號碼⋯⋯等字串打碼:
1use Illuminate\Support\Str;245// tay***************
1use Illuminate\Support\Str;245// tay***************
若有需要,mask
方法的第三個引數可提供負數,這樣 mask
就會從字串結尾起給定的長度開始打碼:
23// tay***@example.com
23// tay***@example.com
Str::orderedUuid()
Str::orderedUuid
方法會產生一個「時戳優先」的 UUID,可用來儲存在有所引的資料庫欄位中。使用本方法產生的 UUID 在排序時會被排到之前使用本方法產生的 UUID 之後:
1use Illuminate\Support\Str;23return (string) Str::orderedUuid();
1use Illuminate\Support\Str;23return (string) Str::orderedUuid();
Str::padBoth()
Str::padBoth
方法包裝了 PHP 的 str_path
方法,會填充字串的兩端,直到字串符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::padBoth('James', 10, '_');45// '__James___'67$padded = Str::padBoth('James', 10);89// ' James '
1use Illuminate\Support\Str;23$padded = Str::padBoth('James', 10, '_');45// '__James___'67$padded = Str::padBoth('James', 10);89// ' James '
Str::padLeft()
Str::padLeft
包裝了 PHP 的 str_pad
方法,會使用另一個字串填充給定字串的左邊,直到符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::padLeft('James', 10, '-=');45// '-=-=-James'67$padded = Str::padLeft('James', 10);89// ' James'
1use Illuminate\Support\Str;23$padded = Str::padLeft('James', 10, '-=');45// '-=-=-James'67$padded = Str::padLeft('James', 10);89// ' James'
Str::padRight()
Str::padRight
包裝了 PHP 的 str_pad
方法,會使用另一個字串填充給定字串的右邊,直到符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::padRight('James', 10, '-');45// 'James-----'67$padded = Str::padRight('James', 10);89// 'James '
1use Illuminate\Support\Str;23$padded = Str::padRight('James', 10, '-');45// 'James-----'67$padded = Str::padRight('James', 10);89// 'James '
Str::plural()
Str::plural
方法將單數單詞轉換為其複數形態。該方法支援所有 Laravel Pluralizer 所支援的語言:
1use Illuminate\Support\Str;23$plural = Str::plural('car');45// cars67$plural = Str::plural('child');89// children
1use Illuminate\Support\Str;23$plural = Str::plural('car');45// cars67$plural = Str::plural('child');89// children
也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:
1use Illuminate\Support\Str;23$plural = Str::plural('child', 2);45// children67$singular = Str::plural('child', 1);89// child
1use Illuminate\Support\Str;23$plural = Str::plural('child', 2);45// children67$singular = Str::plural('child', 1);89// child
Str::pluralStudly()
Str::plural
方法將單數單詞轉換為其複數形態,並以 Studly 命名法 (StudlyCase) 來格式化字串。該方法支援所有 Laravel Pluralizer 所支援的語言:
1use Illuminate\Support\Str;23$plural = Str::pluralStudly('VerifiedHuman');45// VerifiedHumans67$plural = Str::pluralStudly('UserFeedback');89// UserFeedback
1use Illuminate\Support\Str;23$plural = Str::pluralStudly('VerifiedHuman');45// VerifiedHumans67$plural = Str::pluralStudly('UserFeedback');89// UserFeedback
也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:
1use Illuminate\Support\Str;23$plural = Str::pluralStudly('VerifiedHuman', 2);45// VerifiedHumans67$singular = Str::pluralStudly('VerifiedHuman', 1);89// VerifiedHuman
1use Illuminate\Support\Str;23$plural = Str::pluralStudly('VerifiedHuman', 2);45// VerifiedHumans67$singular = Str::pluralStudly('VerifiedHuman', 1);89// VerifiedHuman
Str::random()
Str::random
方法產生指定長度的隨機字串。該函式使用 PHP 的 random_bytes
函式:
1use Illuminate\Support\Str;23$random = Str::random(40);
1use Illuminate\Support\Str;23$random = Str::random(40);
Str::remove()
Str::remove
方法從字串中移除給定的一個或多個值:
1use Illuminate\Support\Str;23$string = 'Peter Piper picked a peck of pickled peppers.';45$removed = Str::remove('e', $string);67// Ptr Pipr pickd a pck of pickld ppprs.
1use Illuminate\Support\Str;23$string = 'Peter Piper picked a peck of pickled peppers.';45$removed = Str::remove('e', $string);67// Ptr Pipr pickd a pck of pickld ppprs.
也可以傳入 false
作為第三個引數給 remove
方法來在移除字串時忽略大小寫差異:
Str::replace()
Str::replace
方法在字串中取代給定字串:
1use Illuminate\Support\Str;23$string = 'Laravel 8.x';45$replaced = Str::replace('8.x', '9.x', $string);67// Laravel 9.x
1use Illuminate\Support\Str;23$string = 'Laravel 8.x';45$replaced = Str::replace('8.x', '9.x', $string);67// Laravel 9.x
Str::replaceArray()
Str::replaceArray
函式使用陣列來依序在陣列中取代給定的值:
1use Illuminate\Support\Str;23$string = 'The event will take place between ? and ?';45$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);67// The event will take place between 8:30 and 9:00
1use Illuminate\Support\Str;23$string = 'The event will take place between ? and ?';45$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);67// The event will take place between 8:30 and 9:00
Str::replaceFirst()
Str::replaceFirst
方法取代字串中第一次出現的給定值:
1use Illuminate\Support\Str;23$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');45// a quick brown fox jumps over the lazy dog
1use Illuminate\Support\Str;23$replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog');45// a quick brown fox jumps over the lazy dog
Str::replaceLast()
Str::replaceLast
方法取代字串中最後一次出現的給定值:
1use Illuminate\Support\Str;23$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');45// the quick brown fox jumps over a lazy dog
1use Illuminate\Support\Str;23$replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog');45// the quick brown fox jumps over a lazy dog
Str::reverse()
Str::reverse
方法反轉給定的字串:
1use Illuminate\Support\Str;23$reversed = Str::reverse('Hello World');45// dlroW olleH
1use Illuminate\Support\Str;23$reversed = Str::reverse('Hello World');45// dlroW olleH
Str::singular()
Str::plural
方法將單詞轉換為其單數形態。該方法支援所有 Laravel Pluralizer 所支援的語言:
1use Illuminate\Support\Str;23$singular = Str::singular('cars');45// car67$singular = Str::singular('children');89// child
1use Illuminate\Support\Str;23$singular = Str::singular('cars');45// car67$singular = Str::singular('children');89// child
Str::slug()
Str::slug
方法以給定字串產生適合在 URL 中使用的「Slug」格式:
1use Illuminate\Support\Str;23$slug = Str::slug('Laravel 5 Framework', '-');45// laravel-5-framework
1use Illuminate\Support\Str;23$slug = Str::slug('Laravel 5 Framework', '-');45// laravel-5-framework
Str::snake()
Str::snake
方法將給定字串轉為 snake_case
—— 蛇型命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::snake('fooBar');45// foo_bar67$converted = Str::snake('fooBar', '-');89// foo-bar
1use Illuminate\Support\Str;23$converted = Str::snake('fooBar');45// foo_bar67$converted = Str::snake('fooBar', '-');89// foo-bar
Str::squish()
Str::squish
方法會從字串內移除所有多餘的空格,其中亦包含單詞間多餘的空格:
1use Illuminate\Support\Str;23$string = Str::squish(' laravel framework ');45// laravel framework
1use Illuminate\Support\Str;23$string = Str::squish(' laravel framework ');45// laravel framework
Str::start()
Str::start
方法會在給定字串不是以給定值起始時,在該字串前方加上這個值:
1use Illuminate\Support\Str;23$adjusted = Str::start('this/string', '/');45// /this/string67$adjusted = Str::start('/this/string', '/');89// /this/string
1use Illuminate\Support\Str;23$adjusted = Str::start('this/string', '/');45// /this/string67$adjusted = Str::start('/this/string', '/');89// /this/string
Str::startsWith()
Str::startsWith` 方法可判斷給定字串是否以給定值起始:
1use Illuminate\Support\Str;23$result = Str::startsWith('This is my name', 'This');45// true
1use Illuminate\Support\Str;23$result = Str::startsWith('This is my name', 'This');45// true
若傳入一組陣列,當字串以給定值中任何一個值開頭時,startsWith
方法會回傳 true
:
1$result = Str::startsWith('This is my name', ['This', 'That', 'There']);23// true
1$result = Str::startsWith('This is my name', ['This', 'That', 'There']);23// true
Str::studly()
Str::studly
方法將給定字串轉為 StudlyCase
—— Studly 命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::studly('foo_bar');45// FooBar
1use Illuminate\Support\Str;23$converted = Str::studly('foo_bar');45// FooBar
Str::substr()
Str::substr
方法回傳字串中指定的起始位置開始指定長度的字串:
1use Illuminate\Support\Str;23$converted = Str::substr('The Laravel Framework', 4, 7);45// Laravel
1use Illuminate\Support\Str;23$converted = Str::substr('The Laravel Framework', 4, 7);45// Laravel
Str::substrCount()
Str::substrCount
方法回傳給定值中給定值出現的次數:
1use Illuminate\Support\Str;23$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');45// 2
1use Illuminate\Support\Str;23$count = Str::substrCount('If you like ice cream, you will like snow cones.', 'like');45// 2
Str::substrReplace()
Str::substrreplace
方法在字串中取代其中一段文字,第三個引數指定起始位置,並以第四個引數來指定要取代的字元數。若第四個引數傳入 0
,則會在指定位置插入字串,而不取代字串中現有的字元:
1use Illuminate\Support\Str;23$result = Str::substrReplace('1300', ':', 2);4// 13:56$result = Str::substrReplace('1300', ':', 2, 0);7// 13:00
1use Illuminate\Support\Str;23$result = Str::substrReplace('1300', ':', 2);4// 13:56$result = Str::substrReplace('1300', ':', 2, 0);7// 13:00
Str::swap()
Str::swap
方法使用 PHP 的 strtr
函式來取代給定字串中的多個值:
1use Illuminate\Support\Str;23$string = Str::swap([4 'Tacos' => 'Burritos',5 'great' => 'fantastic',6], 'Tacos are great!');78// Burritos are fantastic!
1use Illuminate\Support\Str;23$string = Str::swap([4 'Tacos' => 'Burritos',5 'great' => 'fantastic',6], 'Tacos are great!');78// Burritos are fantastic!
Str::title()
Str::title
方法將給定字串轉為 Title Case
—— 標題用的大小寫:
1use Illuminate\Support\Str;23$converted = Str::title('a nice title uses the correct case');45// A Nice Title Uses The Correct Case
1use Illuminate\Support\Str;23$converted = Str::title('a nice title uses the correct case');45// A Nice Title Uses The Correct Case
Str::toHtmlString()
Str::toHtmlString
方法將字串實體轉換為 Illuminate\Support\HtmlString
的實體。HtmlString
實體可以在 Blade 樣板中顯示:
1use Illuminate\Support\Str;23$htmlString = Str::of('Nuno Maduro')->toHtmlString();
1use Illuminate\Support\Str;23$htmlString = Str::of('Nuno Maduro')->toHtmlString();
Str::ucfirst()
Str::ucfirst
方法回傳給定字串第一個字元轉為大寫後的字串:
1use Illuminate\Support\Str;23$string = Str::ucfirst('foo bar');45// Foo bar
1use Illuminate\Support\Str;23$string = Str::ucfirst('foo bar');45// Foo bar
Str::ucsplit()
Str::ucsplit
方法使用大寫字元來將給定字串拆分為陣列:
1use Illuminate\Support\Str;23$segments = Str::ucsplit('FooBar');45// [0 => 'Foo', 1 => 'Bar']
1use Illuminate\Support\Str;23$segments = Str::ucsplit('FooBar');45// [0 => 'Foo', 1 => 'Bar']
Str::upper()
Str::upper
方法將給定字串轉換為大寫:
1use Illuminate\Support\Str;23$string = Str::upper('laravel');45// LARAVEL
1use Illuminate\Support\Str;23$string = Str::upper('laravel');45// LARAVEL
Str::ulid()
Str::ulid
方法可產生 ULID:
1use Illuminate\Support\Str;23return (string) Str::ulid();45// 01gd6r360bp37zj17nxb55yv40
1use Illuminate\Support\Str;23return (string) Str::ulid();45// 01gd6r360bp37zj17nxb55yv40
Str::uuid()
Str::uuid
方法產生 UUID (第 4 版):
1use Illuminate\Support\Str;23return (string) Str::uuid();
1use Illuminate\Support\Str;23return (string) Str::uuid();
Str::wordCount()
Str::wordCount
方法回傳該字串中所包含的單詞數:
1use Illuminate\Support\Str;23Str::wordCount('Hello, world!'); // 2
1use Illuminate\Support\Str;23Str::wordCount('Hello, world!'); // 2
Str::words()
Str::words
方法將字串中的單詞數限制在指定數量內。也可以第三引數來傳入一個額外的字串,用來指定當字串被截斷時要加在最後方的內容:
1use Illuminate\Support\Str;23return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');45// Perfectly balanced, as >>>
1use Illuminate\Support\Str;23return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');45// Perfectly balanced, as >>>
str()
str
會回傳給定字串的 Illuminate\Support\Stringable
實體。這個函式與 Str::of
方法等價:
1$string = str('Taylor')->append(' Otwell');23// 'Taylor Otwell'
1$string = str('Taylor')->append(' Otwell');23// 'Taylor Otwell'
若沒有提供引數給 str
函式,則 str
會回傳一個 Illuminate\Support\Str
的實體:
1$snake = str()->snake('FooBar');23// 'foo_bar'
1$snake = str()->snake('FooBar');23// 'foo_bar'
trans()
trans
函式使用語系檔來翻譯給定的翻譯字串或翻譯索引鍵:
1echo trans('messages.welcome');
1echo trans('messages.welcome');
若指定的翻譯字串或翻譯索引鍵不存在時,trans
函式會回傳給定的值。因此,在上述範例中,若 messages.welcome
索引鍵不存在,trans
函式會回傳 messages.welcome
。
trans_choice()
trans_choice
函式會翻譯有詞形變化的翻譯索引鍵:
1echo trans_choice('messages.notifications', $unreadCount);
1echo trans_choice('messages.notifications', $unreadCount);
若指定的翻譯字串或翻譯索引鍵不存在時,trans_choice
函式會回傳給定的值。因此,在上述範例中,若 messages.notifications
索引鍵不存在,trans_choice
函式會回傳 messages.welcome
。
Fluent 字串
Fluent 字串提供處理字串值一個更流暢、物件導向的介面。我們可以串接多個字串操作,得到比起傳統字串操作來說更好閱讀的語法:
after
after
方法回傳字串中給定值以後的所有內容。若該字串中找不到給定值,會回傳整個字串:
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->after('This is');45// ' my name'
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->after('This is');45// ' my name'
afterLast
afterLast
方法回傳給定字串後最後一個出現給定值之後的所有內容。若找不到該值,會回傳整個字串:
1use Illuminate\Support\Str;23$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');45// 'Controller'
1use Illuminate\Support\Str;23$slice = Str::of('App\Http\Controllers\Controller')->afterLast('\\');45// 'Controller'
append
append
方法將給定的值加到字串最後面:
1use Illuminate\Support\Str;23$string = Str::of('Taylor')->append(' Otwell');45// 'Taylor Otwell'
1use Illuminate\Support\Str;23$string = Str::of('Taylor')->append(' Otwell');45// 'Taylor Otwell'
ascii
ascii
方法會嘗試將給定字串翻譯為 ASCII 值:
1use Illuminate\Support\Str;23$string = Str::of('ü')->ascii();45// 'u'
1use Illuminate\Support\Str;23$string = Str::of('ü')->ascii();45// 'u'
basename
basename
方法回傳給定字串中最後一個名稱部分:
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->basename();45// 'baz'
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->basename();45// 'baz'
若有需要,也可以提供要從最後一個元件中移除的「副檔名」:
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');45// 'baz'
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz.jpg')->basename('.jpg');45// 'baz'
before
before
回傳字串在遇到給定值前的所有內容:
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->before('my name');45// 'This is '
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->before('my name');45// 'This is '
beforeLast
beforeLast
方法回傳字串中最後一次出現給定值以前的所有內容:
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->beforeLast('is');45// 'This '
1use Illuminate\Support\Str;23$slice = Str::of('This is my name')->beforeLast('is');45// 'This '
between
between
方法回傳介於兩個值之間的字串:
1use Illuminate\Support\Str;23$converted = Str::of('This is my name')->between('This', 'name');45// ' is my '
1use Illuminate\Support\Str;23$converted = Str::of('This is my name')->between('This', 'name');45// ' is my '
betweenFirst
betweenFirst
方法回傳介於兩個值之間,最小的可能字串部分:
1use Illuminate\Support\Str;23$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');45// 'a'
1use Illuminate\Support\Str;23$converted = Str::of('[a] bc [d]')->betweenFirst('[', ']');45// 'a'
camel
camel
方法將給定字串轉為 camelCase
—— 駝峰命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::of('foo_bar')->camel();45// fooBar
1use Illuminate\Support\Str;23$converted = Str::of('foo_bar')->camel();45// fooBar
classBasename
classBasename
方法回傳給定類別在移除類別 Namespace 後的類別名稱:
1use Illuminate\Support\Str;23$class = Str::of('Foo\Bar\Baz')->classBasename();45// Baz
1use Illuminate\Support\Str;23$class = Str::of('Foo\Bar\Baz')->classBasename();45// Baz
contains
contains
方法判斷給定字串是否包含給定值。該方法區分大小寫:
1use Illuminate\Support\Str;23$contains = Str::of('This is my name')->contains('my');45// true
1use Illuminate\Support\Str;23$contains = Str::of('This is my name')->contains('my');45// true
也可以傳入一組要判斷的陣列值,來判斷給定字串中是否有包含該陣列中任何一個值:
1use Illuminate\Support\Str;23$contains = Str::of('This is my name')->contains(['my', 'foo']);45// true
1use Illuminate\Support\Str;23$contains = Str::of('This is my name')->contains(['my', 'foo']);45// true
containsAll
containsAll
判斷給定字串是否有包含給定陣列中的所有值:
1use Illuminate\Support\Str;23$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);45// true
1use Illuminate\Support\Str;23$containsAll = Str::of('This is my name')->containsAll(['my', 'name']);45// true
dirname
dirname
方法回傳給定字串中上層目錄的部分:
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->dirname();45// '/foo/bar'
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->dirname();45// '/foo/bar'
若有需要,也可以指定要去的多少層以上的目錄:
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->dirname(2);45// '/foo'
1use Illuminate\Support\Str;23$string = Str::of('/foo/bar/baz')->dirname(2);45// '/foo'
excerpt
excerpt
方法從給定字串中截取摘要,這個摘要符合該字串中第一個符合給定片語 (Phrase) 的實體:
1use Illuminate\Support\Str;23$excerpt = Str::of('This is my name')->excerpt('my', [4 'radius' => 35]);67// '...is my na...'
1use Illuminate\Support\Str;23$excerpt = Str::of('This is my name')->excerpt('my', [4 'radius' => 35]);67// '...is my na...'
radius
選項的預設值為 100
。該選項可用來定義經過截取的字串中左右兩邊各需顯式多少個字元:
此外,也可使用 omission
選項來更改要加到截取字串前後的字串:
1use Illuminate\Support\Str;23$excerpt = Str::of('This is my name')->excerpt('name', [4 'radius' => 3,5 'omission' => '(...) '6]);78// '(...) my name'
1use Illuminate\Support\Str;23$excerpt = Str::of('This is my name')->excerpt('name', [4 'radius' => 3,5 'omission' => '(...) '6]);78// '(...) my name'
endsWith
endsWith
方法可判斷給定字串是否以給定值結尾:
1use Illuminate\Support\Str;23$result = Str::of('This is my name')->endsWith('name');45// true
1use Illuminate\Support\Str;23$result = Str::of('This is my name')->endsWith('name');45// true
也可以傳入一組陣列值來判斷給定字串的結尾是否符合該陣列內的其中一項:
1use Illuminate\Support\Str;23$result = Str::of('This is my name')->endsWith(['name', 'foo']);45// true67$result = Str::of('This is my name')->endsWith(['this', 'foo']);89// false
1use Illuminate\Support\Str;23$result = Str::of('This is my name')->endsWith(['name', 'foo']);45// true67$result = Str::of('This is my name')->endsWith(['this', 'foo']);89// false
exactly
exactly
方法判斷給定字串是否完全符合另一個字串:
1use Illuminate\Support\Str;23$result = Str::of('Laravel')->exactly('Laravel');45// true
1use Illuminate\Support\Str;23$result = Str::of('Laravel')->exactly('Laravel');45// true
explode
explode
方法以給定的分隔符號來拆分字串,並回傳一個包含分割後所有段落的 Collection:
1use Illuminate\Support\Str;23$collection = Str::of('foo bar baz')->explode(' ');45// collect(['foo', 'bar', 'baz'])
1use Illuminate\Support\Str;23$collection = Str::of('foo bar baz')->explode(' ');45// collect(['foo', 'bar', 'baz'])
finish
finish
方法會在給定字串不是以給定值結尾時,在該字串後方加上這個值:
1use Illuminate\Support\Str;23$adjusted = Str::of('this/string')->finish('/');45// this/string/67$adjusted = Str::of('this/string/')->finish('/');89// this/string/
1use Illuminate\Support\Str;23$adjusted = Str::of('this/string')->finish('/');45// this/string/67$adjusted = Str::of('this/string/')->finish('/');89// this/string/
headline
headline
方法將以大小寫、減號、底線等方式區隔的字串轉換為以空格區隔的字串,並將其中每個單詞的首字母都轉為大寫:
1use Illuminate\Support\Str;23$headline = Str::of('taylor_otwell')->headline();45// Taylor Otwell67$headline = Str::of('EmailNotificationSent')->headline();89// Email Notification Sent
1use Illuminate\Support\Str;23$headline = Str::of('taylor_otwell')->headline();45// Taylor Otwell67$headline = Str::of('EmailNotificationSent')->headline();89// Email Notification Sent
inlineMarkdown
inlineMarkdown
方法使用 CommonMarkdown 來將 GitHub Flavored Markdown 轉換為內嵌的 HTML。不過,與 markdown
不同,該方法不會將所有產生的 HTML 以區塊層級的元素包裝起來。
1use Illuminate\Support\Str;23$html = Str::of('**Laravel**')->inlineMarkdown();45// <strong>Laravel</strong>
1use Illuminate\Support\Str;23$html = Str::of('**Laravel**')->inlineMarkdown();45// <strong>Laravel</strong>
is
is
判斷給定字串是否符合給定的格式。可使用星號作為萬用字元:
1use Illuminate\Support\Str;23$matches = Str::of('foobar')->is('foo*');45// true67$matches = Str::of('foobar')->is('baz*');89// false
1use Illuminate\Support\Str;23$matches = Str::of('foobar')->is('foo*');45// true67$matches = Str::of('foobar')->is('baz*');89// false
isAscii
isAscii
方法判斷給定字串是否為 ASCII 字串:
1use Illuminate\Support\Str;23$result = Str::of('Taylor')->isAscii();45// true67$result = Str::of('ü')->isAscii();89// false
1use Illuminate\Support\Str;23$result = Str::of('Taylor')->isAscii();45// true67$result = Str::of('ü')->isAscii();89// false
isEmpty
isEmpty
方法判斷給定字串是否為空:
1use Illuminate\Support\Str;23$result = Str::of(' ')->trim()->isEmpty();45// true67$result = Str::of('Laravel')->trim()->isEmpty();89// false
1use Illuminate\Support\Str;23$result = Str::of(' ')->trim()->isEmpty();45// true67$result = Str::of('Laravel')->trim()->isEmpty();89// false
isNotEmpty
isNotEmpty
方法判斷給定字串是否不為空:
1use Illuminate\Support\Str;23$result = Str::of(' ')->trim()->isNotEmpty();45// false67$result = Str::of('Laravel')->trim()->isNotEmpty();89// true
1use Illuminate\Support\Str;23$result = Str::of(' ')->trim()->isNotEmpty();45// false67$result = Str::of('Laravel')->trim()->isNotEmpty();89// true
isJson
isJson
方法會判斷給定字串是否為有效的 JSON:
1use Illuminate\Support\Str;23$result = Str::of('[1,2,3]')->isJson();45// true67$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();89// true1011$result = Str::of('{first: "John", last: "Doe"}')->isJson();1213// false
1use Illuminate\Support\Str;23$result = Str::of('[1,2,3]')->isJson();45// true67$result = Str::of('{"first": "John", "last": "Doe"}')->isJson();89// true1011$result = Str::of('{first: "John", last: "Doe"}')->isJson();1213// false
isUlid
isUlid
方法判斷給定字串是否為有效的 ULID:
1use Illuminate\Support\Str;23$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();45// true67$result = Str::of('Taylor')->isUlid();89// false
1use Illuminate\Support\Str;23$result = Str::of('01gd6r360bp37zj17nxb55yv40')->isUlid();45// true67$result = Str::of('Taylor')->isUlid();89// false
isUuid
isUuid
方法判斷給定字串是否為有效的 UUID:
1use Illuminate\Support\Str;23$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();45// true67$result = Str::of('Taylor')->isUuid();89// false
1use Illuminate\Support\Str;23$result = Str::of('5ace9ab9-e9cf-4ec6-a19d-5881212a452c')->isUuid();45// true67$result = Str::of('Taylor')->isUuid();89// false
kebab
kebab
方法將給定字串轉換為 kebab-case
—— Kebab 命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::of('fooBar')->kebab();45// foo-bar
1use Illuminate\Support\Str;23$converted = Str::of('fooBar')->kebab();45// foo-bar
lcfirst
lcfirst
方法回傳給定字串第一個字元轉為小寫後的字串:
1use Illuminate\Support\Str;23$string = Str::of('Foo Bar')->lcfirst();45// foo Bar
1use Illuminate\Support\Str;23$string = Str::of('Foo Bar')->lcfirst();45// foo Bar
length
length
方法回傳給定字串的長度:
1use Illuminate\Support\Str;23$length = Str::of('Laravel')->length();45// 7
1use Illuminate\Support\Str;23$length = Str::of('Laravel')->length();45// 7
limit
limit
方法將給定字串截斷成指定長度:
1use Illuminate\Support\Str;23$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);45// The quick brown fox...
1use Illuminate\Support\Str;23$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);45// The quick brown fox...
也可以傳入第二個引數,以更改當字串被截斷時要加在最後方的內容:
1use Illuminate\Support\Str;23$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');45// The quick brown fox (...)
1use Illuminate\Support\Str;23$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20, ' (...)');45// The quick brown fox (...)
lower
lower
方法將給定字串轉為小寫:
1use Illuminate\Support\Str;23$result = Str::of('LARAVEL')->lower();45// 'laravel'
1use Illuminate\Support\Str;23$result = Str::of('LARAVEL')->lower();45// 'laravel'
ltrim
ltrim
方法修剪字串左邊的值:
1use Illuminate\Support\Str;23$string = Str::of(' Laravel ')->ltrim();45// 'Laravel '67$string = Str::of('/Laravel/')->ltrim('/');89// 'Laravel/'
1use Illuminate\Support\Str;23$string = Str::of(' Laravel ')->ltrim();45// 'Laravel '67$string = Str::of('/Laravel/')->ltrim('/');89// 'Laravel/'
markdown
markdown
方法可將 GitHub Flavored Markdown 轉位為 HTML:
1use Illuminate\Support\Str;23$html = Str::of('# Laravel')->markdown();45// <h1>Laravel</h1>67$html = Str::of('# Taylor <b>Otwell</b>')->markdown([8 'html_input' => 'strip',9]);1011// <h1>Taylor Otwell</h1>
1use Illuminate\Support\Str;23$html = Str::of('# Laravel')->markdown();45// <h1>Laravel</h1>67$html = Str::of('# Taylor <b>Otwell</b>')->markdown([8 'html_input' => 'strip',9]);1011// <h1>Taylor Otwell</h1>
mask
mask
方法將字串中的一部分轉為重複字元,可用來為 E-Mail 位址或電話號碼⋯⋯等字串打碼:
1use Illuminate\Support\Str;245// tay***************
1use Illuminate\Support\Str;245// tay***************
若有需要,也可以在 mask
方法的第三個或第四個引數上提供負數。提供負數時,會讓該方法從字串結尾處開始算起的給定距離開始打碼:
23// tay***@example.com467// tayl**********.com
23// tay***@example.com467// tayl**********.com
match
match
方法回傳字串中符合給定正規表示式格式的部分:
1use Illuminate\Support\Str;23$result = Str::of('foo bar')->match('/bar/');45// 'bar'67$result = Str::of('foo bar')->match('/foo (.*)/');89// 'bar'
1use Illuminate\Support\Str;23$result = Str::of('foo bar')->match('/bar/');45// 'bar'67$result = Str::of('foo bar')->match('/foo (.*)/');89// 'bar'
matchAll
matchAll
方法回傳一組 Collection,其中包含字串中所有符合給定正規表示式格式的部分:
1use Illuminate\Support\Str;23$result = Str::of('bar foo bar')->matchAll('/bar/');45// collect(['bar', 'bar'])
1use Illuminate\Support\Str;23$result = Str::of('bar foo bar')->matchAll('/bar/');45// collect(['bar', 'bar'])
也可以在正規式中指定分組,Laravel 會回傳一個包含這些分組的 Collection:
1use Illuminate\Support\Str;23$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');45// collect(['un', 'ly']);
1use Illuminate\Support\Str;23$result = Str::of('bar fun bar fly')->matchAll('/f(\w*)/');45// collect(['un', 'ly']);
若未找到相符合的內容,會回傳空 Collection。
newLine
newLine
方法為字串的最後加上一個「EOL (End of Line,行結尾)」字元:
1use Illuminate\Support\Str;23$padded = Str::of('Laravel')->newLine()->append('Framework');45// 'Laravel6// Framework'
1use Illuminate\Support\Str;23$padded = Str::of('Laravel')->newLine()->append('Framework');45// 'Laravel6// Framework'
padBoth
padBoth
方法包裝了 PHP 的 str_path
方法,會填充字串的兩端,直到字串符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::of('James')->padBoth(10, '_');45// '__James___'67$padded = Str::of('James')->padBoth(10);89// ' James '
1use Illuminate\Support\Str;23$padded = Str::of('James')->padBoth(10, '_');45// '__James___'67$padded = Str::of('James')->padBoth(10);89// ' James '
padLeft
padLeft
包裝了 PHP 的 str_pad
方法,會使用另一個字串填充給定字串的左邊,直到符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::of('James')->padLeft(10, '-=');45// '-=-=-James'67$padded = Str::of('James')->padLeft(10);89// ' James'
1use Illuminate\Support\Str;23$padded = Str::of('James')->padLeft(10, '-=');45// '-=-=-James'67$padded = Str::of('James')->padLeft(10);89// ' James'
padRight
padRight
包裝了 PHP 的 str_pad
方法,會使用另一個字串填充給定字串的右邊,直到符合預期的長度:
1use Illuminate\Support\Str;23$padded = Str::of('James')->padRight(10, '-');45// 'James-----'67$padded = Str::of('James')->padRight(10);89// 'James '
1use Illuminate\Support\Str;23$padded = Str::of('James')->padRight(10, '-');45// 'James-----'67$padded = Str::of('James')->padRight(10);89// 'James '
pipe
pipe
方法會講目前字串傳入給定的閉包內,來讓我們變換字串:
1use Illuminate\Support\Str;23$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');45// 'Checksum: a5c95b86291ea299fcbe64458ed12702'67$closure = Str::of('foo')->pipe(function ($str) {8 return 'bar';9});1011// 'bar'
1use Illuminate\Support\Str;23$hash = Str::of('Laravel')->pipe('md5')->prepend('Checksum: ');45// 'Checksum: a5c95b86291ea299fcbe64458ed12702'67$closure = Str::of('foo')->pipe(function ($str) {8 return 'bar';9});1011// 'bar'
plural
plural
方法將單數單詞轉換為其複數形態。該方法支援所有 Laravel Pluralizer 所支援的語言:
1use Illuminate\Support\Str;23$plural = Str::of('car')->plural();45// cars67$plural = Str::of('child')->plural();89// children
1use Illuminate\Support\Str;23$plural = Str::of('car')->plural();45// cars67$plural = Str::of('child')->plural();89// children
也可以提供一個整數作為該方法的第二個引數,用來判斷要取得該字串的單數或複數型:
1use Illuminate\Support\Str;23$plural = Str::of('child')->plural(2);45// children67$plural = Str::of('child')->plural(1);89// child
1use Illuminate\Support\Str;23$plural = Str::of('child')->plural(2);45// children67$plural = Str::of('child')->plural(1);89// child
prepend
prepend
方法將給定的值加到字串最後面:
1use Illuminate\Support\Str;23$string = Str::of('Framework')->prepend('Laravel ');45// Laravel Framework
1use Illuminate\Support\Str;23$string = Str::of('Framework')->prepend('Laravel ');45// Laravel Framework
remove
remove
方法從字串中移除給定的一個或多個值:
1use Illuminate\Support\Str;23$string = Str::of('Arkansas is quite beautiful!')->remove('quite');45// Arkansas is beautiful!
1use Illuminate\Support\Str;23$string = Str::of('Arkansas is quite beautiful!')->remove('quite');45// Arkansas is beautiful!
也可以傳入 false
作為第二個引數,來在移除字串時忽略大小寫差異:
replace
replace
方法在字串中取代給定字串:
1use Illuminate\Support\Str;23$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');45// Laravel 7.x
1use Illuminate\Support\Str;23$replaced = Str::of('Laravel 6.x')->replace('6.x', '7.x');45// Laravel 7.x
replaceArray
replaceArray
函式使用陣列來依序在陣列中取代給定的值:
1use Illuminate\Support\Str;23$string = 'The event will take place between ? and ?';45$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);67// The event will take place between 8:30 and 9:00
1use Illuminate\Support\Str;23$string = 'The event will take place between ? and ?';45$replaced = Str::of($string)->replaceArray('?', ['8:30', '9:00']);67// The event will take place between 8:30 and 9:00
replaceFirst
replaceFirst
方法取代字串中第一次出現的給定值:
1use Illuminate\Support\Str;23$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');45// a quick brown fox jumps over the lazy dog
1use Illuminate\Support\Str;23$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceFirst('the', 'a');45// a quick brown fox jumps over the lazy dog
replaceLast
replaceLast
方法取代字串中最後一次出現的給定值:
1use Illuminate\Support\Str;23$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');45// the quick brown fox jumps over a lazy dog
1use Illuminate\Support\Str;23$replaced = Str::of('the quick brown fox jumps over the lazy dog')->replaceLast('the', 'a');45// the quick brown fox jumps over a lazy dog
replaceMatches
replaceMatches
方法使用給定取代字串來取代字串中所有符合格式的部分:
1use Illuminate\Support\Str;23$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')45// '15015551000'
1use Illuminate\Support\Str;23$replaced = Str::of('(+1) 501-555-1000')->replaceMatches('/[^A-Za-z0-9]++/', '')45// '15015551000'
replaceMatches
也接受一個閉包,每當有符合格式的部分時,就會將符合的部分傳給該閉包,讓我們能在閉包內處理取代邏輯,並在閉包內回傳要取代的值:
1use Illuminate\Support\Str;23$replaced = Str::of('123')->replaceMatches('/\d/', function ($match) {4 return '['.$match[0].']';5});67// '[1][2][3]'
1use Illuminate\Support\Str;23$replaced = Str::of('123')->replaceMatches('/\d/', function ($match) {4 return '['.$match[0].']';5});67// '[1][2][3]'
rtrim
rtrim
方法修剪字串右邊的值:
1use Illuminate\Support\Str;23$string = Str::of(' Laravel ')->rtrim();45// ' Laravel'67$string = Str::of('/Laravel/')->rtrim('/');89// '/Laravel'
1use Illuminate\Support\Str;23$string = Str::of(' Laravel ')->rtrim();45// ' Laravel'67$string = Str::of('/Laravel/')->rtrim('/');89// '/Laravel'
scan
scan
方法依照給定的格式來講輸入字串解析為 Collection。給定的格式為 sscanf
PHP 函式所支援的:
1use Illuminate\Support\Str;23$collection = Str::of('filename.jpg')->scan('%[^.].%s');45// collect(['filename', 'jpg'])
1use Illuminate\Support\Str;23$collection = Str::of('filename.jpg')->scan('%[^.].%s');45// collect(['filename', 'jpg'])
singular
plural
方法將單詞轉換為其單數形態。該方法支援所有 Laravel Pluralizer 所支援的語言:
1use Illuminate\Support\Str;23$singular = Str::of('cars')->singular();45// car67$singular = Str::of('children')->singular();89// child
1use Illuminate\Support\Str;23$singular = Str::of('cars')->singular();45// car67$singular = Str::of('children')->singular();89// child
slug
slug
方法以給定字串產生適合在 URL 中使用的「Slug」格式:
1use Illuminate\Support\Str;23$slug = Str::of('Laravel Framework')->slug('-');45// laravel-framework
1use Illuminate\Support\Str;23$slug = Str::of('Laravel Framework')->slug('-');45// laravel-framework
snake
snake
方法將給定字串轉為 snake_case
—— 蛇型命名法的大小寫:
1use Illuminate\Support\Str;23$converted = Str::of('fooBar')->snake();45// foo_bar
1use Illuminate\Support\Str;23$converted = Str::of('fooBar')->snake();45// foo_bar
split
split
方法使用正規表示式來將字串拆分為 Collection:
1use Illuminate\Support\Str;23$segments = Str::of('one, two, three')->split('/[\s,]+/');45// collect(["one", "two", "three"])
1use Illuminate\Support\Str;23$segments = Str::of('one, two, three')->split('/[\s,]+/');45// collect(["one", "two", "three"])
squish
squish
方法會從字串內移除所有多餘的空格,其中亦包含單詞間多餘的空格:
1use Illuminate\Support\Str;2 3$string = Str::of(' laravel framework ')->squish();