belca / support
Belca组件和任何PHP项目使用的辅助函数和类。
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^6
Suggests
- illuminate/support: Needs for to uses Belca\Support\ServiceProvider version 5.*
README
文档适用于版本 v0.10。
辅助类和其函数可以在任何PHP项目中使用。
辅助类用于Belca组件。
常量与枚举(Constants & Enum)
命名常量和枚举用于不可变的值。以下类包含提取常量列表和获取常量而不抛出异常的功能。
AbstractConstants
AbstractConstants - 实现命名常量和获取其值的抽象类。
可能你只会使用一个常量类,那么它可能如下所示。
use Belca\Support\AbstractConstants; class FirstConstants extends AbstractConstants { const USER = 'user'; const SUPERUSER = 'superuser'; const CLIENT = 'client'; const MODERATOR = 'moderator'; const SUPERMODERATOR = 'super'.self::USER; }
在类 FirstConstants
中我们声明了所有需要的常量。一段时间后我们有了添加更多常量的需求。我们可以在同一个类中实现,但如果我们在开发包,那么它将如下所示。
class SecondConstants extends FirstConstants { const VIEWER = 'viewer'; const CHECKER = 'checker'; const TESTER = 'tester'; const SUPERUSER = 'root'; // заменяет предыдущее значение const SUPERMODERATOR = 'supermoderator'; // заменяет предыдущее значение }
在新的常量类中,我们可以重写之前声明的值。
让我们看看如何使用我们创建的类。
// Получим все константы классов $allFirstConstants = FirstConstants::getConstants(); $allSecondConstants = SecondConstants::getConstants(); // Output $allFirstConstants: [ // 'USER' => 'user', // 'SUPERUSER' => 'superuser', // 'CLIENT' => 'client', // 'MODERATOR' => 'moderator', // 'SUPERMODERATOR' => 'superuser', // ] // // Output $allSecondConstants: [ // 'USER' => 'user', // 'SUPERUSER' => 'root', // 'CLIENT' => 'client', // 'MODERATOR' => 'moderator', // 'SUPERMODERATOR' => 'superuser', // 'VIEWER' => 'viewer', // 'CHECKER' => 'checker', // ] // Получим конкретные константы FirstConstants $user = FirstConstants::getConst('USER'); // 'user' $superuser = FirstConstants::getConst('SUPERUSER'); // 'superuser' $root = FirstConstants::getConst('ROOT'); // null // Получим конкретные константы SecondConstants $user = SecondConstants::getConst('USER'); // 'user' $superuser = SecondConstants::getConst('SUPERUSER'); // 'root' $root = SecondConstants::getConst('ROOT'); // null // Проверим существование констант SecondConstants::isDefined('SUPERUSER'); // true SecondConstants::isDefined('ROOT'); // false
在上面的例子中,我们获取了所有常量,获取了具体的常量,尝试获取一个不存在的常量,并在类中检查了常量是否存在。
当然,我们可以直接访问特定的常量,但访问一个不存在的常量将会抛出异常。因此,最好使用类的功能。
$superuser = SecondConstants::SUPERUSER; // 'root' $root = SecondConstants::ROOT; // Error: Undefined class constant 'ROOT'
AbstractEnum
AbstractEnum - 实现命名常量和返回其值的抽象类。与 Belca\Support\AbstractConstants
类不同,Belca\Support\AbstractEnum
类使用默认常量。
实现自 AbstractEnum
的类函数与 AbstractConstants
类相同,除了有一个新的函数 - getDefault()
。类的实现也有所不同。
use Belca\Support\AbstractEnum; class FirstConstants extends AbstractEnum { const DEFAULT = self::USER; const USER = 'user'; const SUPERUSER = 'root'; const CLIENT = 'client'; }
$defaultValue = FirstConstants::getDefault(); // 'user'
扩展类时,我们可以重写默认值。
数组(Arrays)- 处理数组的函数
Belca\Support\Arr
类用于处理简单数据集的数组(与 Belca\Support\SpecialArr
类处理的数据不同,数组的数据和键不需要遵循特殊的存储规则)。
要使用类的函数,需要引入它或通过指定完整的类路径调用其函数。以下展示了如何引入和使用类的函数。
use Belca\Support\Arr; // или $result = \Belca\Support\Arr::trim($array); // и другие функции
Arr::trim
Arr::trim(array $array) : array
使用 trim()
函数删除数组字符串值中的额外空格、制表符和换行符。数组键保持不变。
$array = [ ' value ', 'trim', 'one ', ' two', ' three ', 1, 2, 'string', null, [' no trim '], ]; $result = Arr::trim($array); // Output: ['value', 'trim', 'one', 'two', 'three', 1, 2, 'string', null, [' no trim ']];
如果传入的参数不是数组,则返回空数组。
$notArray = null; $result = Arr::trim($notArray); // Output: [];
此功能不处理嵌套数组中的值。
Arr::removeEmpty
Arr::removeEmpty(array $array) : array
使用 empty()
函数检查数组中的空值,并删除空值。数组键保持不变。
如果传入的参数不是数组,则返回空数组。
$array4 = [1, 2, null, '', [], new stdClass, false, 0]; $result = Arr::removeEmpty($array); // Output: [1, 2, 5 => new stdClass];
Arr::removeNull
Arr::removeNull(array $array) : array
使用 is_null()
函数删除数组中值为 null 的元素。数组键保持不变。
如果传入的参数不是数组,则返回空数组。
$array = [1, 2, null, '', [], new stdClass, false, 0]; $result = Arr::removeNull($array); // Output: [1, 2, 3 => '', [], new stdClass, false, 0];
Arr::removeNotScalar
Arr::removeNotScalar(array $array) : array
删除数组中值为 'null' 或非标量值(标量值:整数、浮点数、字符串、布尔值)的元素。数组键保持不变。
$array = [1, 2, null, '', [], new stdClass, false, 0]; $result = Arr::removeNotScalar($array); // Output: [0 => 1, 1 => 2, 3 => '', 6 => false, 7 => 0];
Arr::removeEmptyRecurcive
Arr::removeEmptyRecurcive(array $array, boolean $resetIndex = true) : array
递归地删除多维数组中的空值。
如果指定的值不是数组,则将返回该值不变。
函数参数
- $array - 任意数组;
- $resetIndex - 重置数组。如果 $resetIndex 为 true,则重置数组中的数值键,包括手动指定的键,而不是在初始化数组时自动分配的键。
$array = [ 1 => [1, 2, 3 => [1, 2, 3, 4, [], null], 4, ''], -2, 'a3' => [ 1, 2, 'a3.3' => [0, 1, 2, 3], ], null, '', 0, false, ]; $result = Arr::removeEmptyRecurcive($array); // Output: // [ // 1 => [0 => 1, 1 => 2, 2 => [1, 2, 3, 4], 3 => 4], // 2 => -2, // 'a3' => [ // 0 => 1, // 1 => 2, // 'a3.3' => [0 => 1, 1 => 2, 2 => 3], // ], // ]
在上面的示例中,仅当所有键都是数字时才会重置键。因此,数组的键和值 $arrar['a3']
保持不变,而所有其他键都被置零。
$array = [ 1 => [1, 2, 3 => [1, 2, 3, 4, [], null], 4, ''], -2, 'a3' => [ 1, 2, 'a3.3' => [0, 1, 2, 3], ], null, '', 0, false, ]; $result = Arr::removeEmptyRecurcive($array, false); // Output: // [ // 1 => [1, 2, 3 => [1, 2, 3, 4], 4 => 4], // 2 => -2, // 'a3' => [ // 0 => 1, // 1 => 2, // 'a3.3' => [1 => 1, 2 => 2, 3 => 3], // ], // ]
在上面的示例中,所有键保持不变,因为我们把 $resetIndex 设置为 false。
Arr::removeNullRecurcive
Arr::removeNullRecurcive(array $array, boolean $resetIndex = true) : array
递归地删除多维数组中等于 null 的值。
函数参数
- $array - 任意数组;
- $resetIndex - 重置索引。如果 $resetIndex 为 true,则在所有内部数组中重置数值键。如果处理数组中至少有一个非数值键,则所有键(包括处理数组的数值键)保持不变。
$array = [ 1 => [1, 2, 3 => [1, 2, 3, 4, [], null], 4, ''], -2, 4 => [ 1 => 1, 2 => 2, 'a3.3' => [0, 1, 2, 3], ], null, '', 0, false, ]; $result = Arr::removeNullRecurcive($array); // Output: // [ // 0 => [0 => 1, 1 => 2, 2 => [1, 2, 3, 4, []], 3 => 4, 4 => ''], // 1 => -2, // 2 => [ // 1 => 1, // 2 => 2, // 'a3.3' => [0 => 1, 1 => 2, 2 => 3], // ], // 3 => '', // 4 => 0, // 5 => false, // ]
在上面的示例中,如果处理数组的所有键都是数值的,则发生键的重置。因此,值 $array[2]
的键保持不变,尽管该值的索引已经改变。
在下例中,所有键保持不变。
$array = [ 1 => [1, 2, 3 => [1, 2, 3, 4, [], null], 4, ''], -2, 4 => [ 1 => 1, 2 => 2, 'a3.3' => [0, 1, 2, 3], ], null, '', 0, false, ]; $result = Arr::removeNullRecurcive($array, false); // Output: // [ // 1 => [1, 2, 3 => [1, 2, 3, 4, []], 4 => 4, 5 => ''], // 2 => -2, // 4 => [ // 1 => 1, // 2 => 2, // 'a3.3' => [1 => 1, 2 => 2, 3 => 3], // ], // 6 => '', // 7 => 0, // 8 => false, // ]
Arr::isArrayWithIntKeys
Arr::isArrayWithIntKeys(array $array) : boolean
检查数组中的键是否为数值。可用于检查数组是否为关联数组。
仅当所有键都是数值时返回 true。空数组不是数值,因为其键和值尚未定义。
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 10]; // true $array2 = []; // false $array3 = 1; // false $array4 = ['1' => 1, 2, 3, '4' => 4]; // true $array5 = [50 => 1, 'a2' => 3, 'a3' => 4, 0 => 1]; // false $result1 = Arr::isArrayWithIntKeys($array1); // true $result2 = Arr::isArrayWithIntKeys($array2); // false, потому что пустой массив $result3 = Arr::isArrayWithIntKeys($array3); // false, потому что не массив $result4 = Arr::isArrayWithIntKeys($array4); // true, потому что числа в строке преобразованы в integer $result5 = Arr::isArrayWithIntKeys($array5); // false
Arr::isIntKeys
Arr::isIntKeys(array $array) : boolean
函数 Arr::isArrayWithIntKeys()
的同义词。
$normalArray = [1, 2, 3, 4, 5, 6, 7, 8, 10]; // true $badArray = [50 => 1, 'a2' => 3, 'a3' => 4, 0 => 1]; // false $result1 = Arr::isIntKeys($normalArray); // true $result2 = Arr::isIntKeys($badArray); // false
Arr::isFirstLastWithIntKeys
Arr::isFirstLastWithIntKeys(array $array) : boolean
检查数组中的第一个和最后一个值是否具有数值键。
此简单算法有助于确定数组的关联性。实际上,这是函数 isArrayWithIntKeys()
的类似物,但在本例中,传递数组的所有键都必须属于同一类型(即要么是数值,要么是字符串)。
在传递空数组或非数组时,函数的结果将是 false。
$array1 = [1, 2, 3, 4, 5, 6, 7, 8, 10]; // true $array2 = []; // false $array3 = 1; // false $array4 = ['1' => 1, 2, 3, '4' => 4]; // true $array5 = [50 => 1, 'a2' => 3, 'a3' => 4, 0 => 1]; // true $array6 = [50 => 1, 'a2' => 3, 'a3' => 4, 'one' => 1]; // false $result1 = Arr::isFirstLastWithIntKeys($array1); // true $result2 = Arr::isFirstLastWithIntKeys($array2); // false, потому что пустой массив $result3 = Arr::isFirstLastWithIntKeys($array3); // false, потому что не массив $result4 = Arr::isFirstLastWithIntKeys($array4); // true, потому что числа в строке преобразованы в integer $result5 = Arr::isFirstLastWithIntKeys($array5); // true, потому что первый и последний ключ является числовым $result6 = Arr::isFirstLastWithIntKeys($array6); // false, потому что последний ключ строка
与函数 Arr::isArrayWithIntKeys()
不同,后者可以遍历整个数组,当前函数仅检查第一个和最后一个值,因此执行速度更快。
Arr::concatArray
Arr::concatArray(&$source, $array, $replace = true) : void
向指定的数组添加新的键和值数组到数组的末尾。
该函数替换了 $array1 += $array2
和 $array2 + $array1
操作,具体取决于传递的参数 $replace。
函数参数
- &$source - 原始数组(使用数组引用);
- $array - 要添加的数组;
- $replace - 替换值。如果 $replace 为 true,则所有具有相同键的现有值将被新值替换。
** 示例 1:向数组添加新值并替换具有相同键的值,具有数值键的数组。**
$source = [1, 2, 3, 4, 5, 6]; $array = [6, 7, 8, 9, 10, 11, 12]; Arr::concatArray($source, $array); // Output $source: [6, 7, 8, 9, 10, 11, 12];
在上面的示例中,可能会出现意外的结果,因为所有值都被新的数组值覆盖了。这是由于所有键都相同,只添加了一个新的值 - 12。
** 示例 2:向数组添加新值并替换具有相同键的值,具有数值键的数组。数值键的偏移。**
$source = [1, 2, 3, 4, 5, 6]; $array = [6 => 6, 7, 8, 9, 10, 11, 12]; Arr::concatArray($source, $array); // Output $source: [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12];
在上面的例子中,我们得到了我们需要的结果,即已经将新值添加到传递的数组中。这种结果在处理关联数组时非常有用。
下面的例子中,我们使用了一个关联数组,其中将覆盖添加数组中具有相同键的值。
** 示例 3:在数组中添加新值并替换具有相同键的旧值。**
$source = ['key1' => 1, 'key2' => 2]; $newValues = ['key2' => 3, 'key3' => 4]; Arr::concatArray($source, $newValues); // Output $source: ['key1' => 1, 'key2' => 3, 'key3' => 4];
并不总是有用替换原始数组中的值,有时可能需要仅添加原始数组中尚不存在的新值。
下面是一个这样的例子。
** 示例 4:仅向数组添加新值。**
$source = ['key1' => 1, 'key2' => 2]; $newValues = ['key2' => 3, 'key3' => 4]; Arr::concatArray($source, $newValues, false); // Output $source: ['key1' => 1, 'key2' => 2, 'key3' => 4];
正如你所看到的,这个函数不返回结果,而是直接操作原始数组,即通过引用传递。
Arr::removeArrays
Arr::removeArrays($array, $resetIndex = false) : array
从数组中删除嵌套数组(子数组)。
函数参数
- $array - 任意数组;
- $resetIndex - 重置数组。如果 $resetIndex - true,则重置数组键。
** 示例 1:删除内部数组。**
$array = [ 1, 2, 3, 'four' => 4, 'five' => 5, 'matrix' => [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ], 7, 'eight' => 8, 9, 'symbols' => ['a', 'b', 'c'], 'object' => new stdClass(), ]; $result = Arr::removeArrays($array); // Output: [ // 1, // 2, // 3, // 'four' => 4, // 'five' => 5, // 7, // 'eight' => 8, // 9, // 'object' => new stdClass(), // ];
在上面的例子中,我们删除了所有数组,并留下了其他值。
有时在执行此操作时可能需要重置数组键,如下面的例子所示。
** 示例 2:删除内部数组并重置数组键。**
$array = [ 1, 2, 3, 'four' => 4, 'five' => 5, 'matrix' => [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ], 7, 'eight' => 8, 9, 'symbols' => ['a', 'b', 'c'], 'object' => new stdClass(), ]; $result = Arr::removeArrays($array); // Output: [1, 2, 3, 4, 5, 7, 8, 9, new stdClass()];
Arr::last
Arr::last(&$array) : mixed
该函数返回数组的最后一个元素。尽管函数接收数组的引用,但内部数组指针不会被重置。
$array = [5 => 1, 2, 3, 4, 5]; $last = Arr::last($array); // Output: 5
Arr::unset
Arr::unset($array, ...$indexes) : array
删除指定的索引,并返回包含剩余索引的修改后的数组。
$array = [ 1, 2, 3, 'four' => 4, 'five' => 5, 'matrix' => [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ], 7, 'eight' => 8, 9, 'symbols' => ['a', 'b', 'c'], 'object' => new stdClass(), ]; $output = Arr::unset($array, 0, 'four', 'eight', 4); $output = Arr::unset($array, [0, 'four', 'eight', 4]); $output = Arr::unset($array, [0, 'four'], ['eight', 4]); $output = Arr::unset($array, [0, 'four'], [['eight'], [4], []]); // Output: // [ // 1 => 2, // 2 => 3, // 'five' => 5, // 'matrix' => [ // [1, 2, 3], // [4, 5, 6], // [7, 8, 9], // ], // 3 => 7, // 'symbols' => ['a', 'b', 'c'], // 'object' => new stdClass(), // ]
如上面的例子所示,该函数几乎接受任何可接受的关键字和可能包含关键字的嵌套数组。
当需要从数组中删除已知索引的未知值时,该函数非常有用。可以使用 array_filter()
函数达到类似的效果,但这个函数更易于阅读、更紧凑且更通用。
Arr::pushArray
Arr::pushArray(&$array, ...$array) : void
将其他数组的值附加到基本数组上。具有字符串键的值将在匹配时被替换,而具有数字键的值将被添加。
$source = [1, 2, 3, 'key1' => 1, 'key2' => 2, 'key3' => 3]; $array1 = [4, 5, 6]; $array2 = [1, 2, 3, 'key1' => 10]; Arr::pushArray($source, $array1, $array2); // Output $source: // [1, 2, 3, 'key1' => 10, 'key2' => 2, 'key3' => 3, 4, 5, 6, 1, 2, 3]
请注意示例的结果。来自 $array2 的 1, 2, 3 值被添加到原始数组中,而数组中已经存在这些元素,因此出现了重复值。
如果您不需要数组中有重复值,则可以使用 array_unique()
函数来返回仅包含唯一值的数组,但这也会影响到具有字符串键的值,其中不同的键可能具有相同的值。
特殊数组处理函数
Belca\Support\SpecialArr
类的函数旨在处理存储在特定规则中的值并使用相应的函数进行处理。
SpecialArr::originalKeys
SpecialArr::originalKeys($array)
返回数组的原始键,前提是传递了包含键的数组,包括二维数组,其中作为嵌套数组值的字符串是键的别名。
** 示例 1:使用别名获取键。**
$array = ['finfo.created', 'finfo.size' => 'filesize', 'finfo.mime' => 'mime']; $keys = SpecialArr::originalKeys($array); // Output: ['finfo.created', 'finfo.size', 'finfo.mime']
** 示例 2:不使用别名获取键。**
$array = ['finfo.created', 'finfo.size', 'finfo.mime']; $keys = SpecialArr::originalKeys($array); // Output: ['finfo.created', 'finfo.size', 'finfo.mime']
在最后一个函数示例中,我们得到了一个等价的数组。该函数主要针对使用键别名或其他值的数组。
SpecialArr::doubleImplode
SpecialArr::doubleImplode($array = [], $chainLinks = ["", "", ""], $glue = "")
函数参数
- $array - 关联数组;
- $chainLinks - 内部数组值的连接符;
- $glue - 数组最终值的连接符。
此函数用于合并数组和其值,通过插入指定的分隔符号。
** 示例 1:合并标签属性 **
$array = [ 'name' => 'phone', 'maxlength' => 20, 'class' => 'input input_type_primary input_width_medium', 'required' => true, ]; $result = SpecialArr::doubleImplode($array, ["", "=\"", "\""], " "); // Output: 'name="phone" maxlength="20" class="input input_type_primary input_width_medium" required'
请注意,逻辑属性已被替换为不带赋值的键名 true。需要注意的是,如果指定为 false,则值将被忽略。
SpecialArr::pullThroughSeparator
SpecialArr::pullThroughSeparator($array, $target, $separator = '.')
使用分隔符从多维数组中提取值。
函数参数
- $array - 多维关联数组;
- $target - 由分隔符(例如'.')分隔的键链,用于访问数组元素;
- $separator - 字符串分隔符或符号分隔符。
$array = [ 'finfo' => [ 'size' => 998, 'mime' => 'image/png', ], ]; $value = SpecialArr::pullThroughSeparator($array, 'finfo.size'); // Output: 998 $value = SpecialArr::pullThroughSeparator($array, 'finfo'); // Output: [ // 'size' => 998, // 'mime' => 'image/png' // ] $value = SpecialArr::pullThroughSeparator($array, 'finfo.date'); // Output: null
如您所注意到的,该函数类似于Laravel中的Arr::get($array, 'path.to.value')
函数,但除了可以更改分隔符之外。
HTML - HTML处理函数
该类用于处理字符串表示的HTML片段和HTML文档。
通过导入类 Belca\Support\HTML
来开始使用它。
use Belca\Support\HTML;
HTML::removeTags
HTML::removeTags($html, $allowedTags = [], $clearTags = true, $allowedAttributes = [])
该函数删除指定HTML内容的标签。可以指定允许的标签并仅保留允许的标签属性。
函数参数
- $html - HTML文档的字符串片段;
- $allowedTags - 允许的标签(例外);
- $clearTags - 清除标签。如果 $clearTags 为 true,则删除标签内的属性,否则属性将保持不变;
- $allowedAttributes - 允许的标签属性数组。如果启用清除标签属性,则所有标签属性都将变为空。这也影响了单标签,如img、input、meta等元素,这些元素如果没有属性则没有意义。为了避免这种情况,需要在此列出所有必要的属性,例如src、content、name。
示例 1:删除所有标签。
$html = "<p><b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $html = HTML::removeTags($html); // Output: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
示例 2:删除所有标签(除允许的标签外)。
$html = "<p><b class='color_red'>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $allowedTags = ['b', 'hr']; $html = HTML::removeTags($html); // Output: "<b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
请注意,所有标签的 b 属性也将被删除。
示例 3:删除所有标签(除允许的标签外),保留标签中必要的属性。
$html = "<p><b class='color_red' style='color: green;'>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $allowedTags = ['b', 'hr']; $clearTags = true; $allowedAttributes = ['class']; $html = HTML::removeTags($html, $allowedTags, $clearTags, $allowedAttributes); // Output: "<b class='color_red'>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
示例 4:删除所有标签(除允许的标签外),保留标签中的所有属性。
此函数的结果可能不安全,因为如果允许如script、style等标签,则生成的代码可能会执行并更改显示的内容,这可能对用户来说是不希望看到的。
$html = "<p><b class='color_red' style='color: green;'>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $allowedTags = ['b', 'hr']; $html = HTML::removeTags($html, $allowedTags, false); // Output: "<b class='color_red' style='color: green;'>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
有时,除了删除标签,还需要删除标签的内容。为此,请使用函数 HTML::removeTagContent()
。
HTML::removeTagContent
HTML::removeTagContent($html, $tags = [])
该函数删除指定标签的内容和标签本身。删除从标签开始到标签结束的数据,不涉及周围的空格、制表符和换行符。
函数参数
- $html - HTML文档的字符串片段;
- $tags - 要删除的标签数组。标签及其内容将被删除。
在下面的示例中,我们指定了包含整个内容的 p 标签。我们还指定了 b、br、img 标签,但在本例中,除了 p 标签外的其他标签并不重要,因为该标签中的所有内容都将被删除。
$html = "<p><b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $html = HTML::removeTagContent($html, $tags = ['p', 'b', 'br', 'img']); // Output: ''
在下面的示例中,我们指定了 b、br、img 标签的内容将被删除。由于 br 和 img 是单标签,因此它们下面没有内容,但它们也将被删除。
$html = "<p><b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $html = HTML::removeTagContent($html, $tags = ['b', 'br', 'img']); // Output: "<p> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>";
请注意 p 标签中的 'sit' 前面的空格没有被删除,因为它不是标签的一部分。在删除标签时需要考虑这一点。
HTML::removeSingleTags
HTML::removeSingleTags($html, $allowed = [])
该函数删除除了允许的标签之外的单标签。
函数参数
- $html - HTML文档的字符串片段;
- $allowed - 允许的标签。允许的标签不会被删除,即这是例外。
单标签列表: area, base, basefont (已废弃的标签), bgsound (非标准标签), br, col, command, doctype, embed, hr, img, input, isindex (已废弃的标签), keygen, link, meta, param, source, track, xml, wbr.
$html = "<p><b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><img src='/path/to/img.jpg'></p>"; $html = HTML::removeSingleTags($html, $allowed = ['hr']); // Output: "<p><b>Lorem ipsum dolor</b> sit amet, consectetur adipisicing elit, <hr> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>";
HTML::removeTagAttributes
HTML::removeTagAttributes($html, $allowedAttributes = [])
该函数删除标签的属性,只保留允许的属性。在完全清除标签属性时,将创建一个新的HTML5格式的属性,因此所有标签都将使用格式,即使是没有结束符的单标签。
HTTP
要使用类中的函数,请连接到类Belca\Support\HTTP
。
use Belca\Support\HTTP;
HTTP::parseAcceptLanguage
解析HTTP头部字符串'HTTP_ACCEPT_LANGUAGE',并返回数组。
$languages = HTTP::parseAcceptLanguage("ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3"); // Output $languages: // [ // "ru-RU" => 1, // "ru" => 0.8, // "en-US" => 0.5, // "en" => 0.3 // ];
字符串 - 字符串处理函数
要使用函数,请连接到类Belca\Support\Str
。
use Belca\Support\Str;
Str::removeDuplicateSymbols
Str::removeDuplicateSymbols($string, $symbols, $number = 2, $strict = false)
该函数在字符串中缩减重复的符号(重复的子串)。
函数参数
- $string - 要处理的字符串;
- $symbols - 要查找的符号(一个符号或字符串);
- $number - 重复的最小次数或精确的重复次数,取决于参数 $strict。这里的重复指的是重复的子串或符号(2个及以上),即符号A的重复意味着在子串中出现了两个符号A - AA;
- $strict - 精确的符号数量。如果为true,则删除精确的重复次数的字符串,而不是最小重复次数。
最好通过例子来了解函数的工作。
在下面的例子中,搜索并删除值'A'直到出现2次及以上的值。函数将重复的符号'A'缩减为一个。
$source = "AABC aabbcc A A aaaaAAAA A A A B B"; $result = Str::removeDuplicateSymbols($source, 'A ', 1); // 1+1 = 2 и более вхождений в подстроку // Output: "ABC aabbcc A A aaaaA A A A B B"
有时需要找到并缩减特定的重复值,如下面的例子所示。所有重复的符号都缩减为两个重复。
$source = "AABC aabbcc A A aaaaAAAA A A A B B"; $result = Str::removeDuplicateSymbols($source, 'A', 1, true); // 1+1 = 2 вхождения // Output: "ABC aabbcc A A aaaaAA A A A B B"
Str::reduceDuplicateSymbols
Str::reduceDuplicateSymbols($string, $symbols, $number = 1)
函数参数
- $string - 要处理的字符串;
- $symbols - 要减少的符号或符号集合;
- $number - 重复的符号数量。值为1时,减少连续符号的数量至1个,2时减少至2个,依此类推。
该函数将连续重复的符号数量减少到指定的值。
在下面的例子中,符号'A'的数量被减少到2个在字符集aaaaAAAA
中(aaaaAAAA
-> aaaaAA
)。当处理单个符号时,这似乎并没有什么不同。
$source = "ABC aabbcc aaaaAAAA A A A B B B A A A"; $result = Str::reduceDuplicateSymbols($source, 'A', 2); // Output: "ABC aabbcc aaaaAA A A A B B B A A A"
在另一个例子中,我们处理的是两个符号的序列:'A'和' '。如果不理解例子,可以假设结果将是 'ABC aabbcc aaaaAAAA A A B B B A A A',但事实上我们得到的是 ABC aabbcc aaaaAAAA A A B B B A A A A
。这是因为在字符串的末尾没有空格,就像原始表达式一样。在搜索和替换值时需要考虑这一点。
$source = "ABC aabbcc aaaaAAAA A A A B B B A A A"; $result = Str::reduceDuplicateSymbols($source, 'A ', 2); // Output: "ABC aabbcc aaaaAAAA A A B B B A A A"
Str::normalizeFilePath
Str::normalizeFilePath($string)
该函数从字符串中删除多余的斜杠(符号'/')并返回新的字符串。
$path = "//path///to//directory/"; $path = Str::normalizeFilePath($path); // Output: "/path/to/directory/"
Str::differenceSubstring
Str::differenceSubstring($sourceString, $secondString)
如果字符串是另一个字符串的子串,则返回字符串的差异,否则返回null。字符串的传递顺序无关紧要。如果传递的值不是字符串,则返回null。
该函数的典型使用案例是确定不同的目录路径。以下是一个示例。
$sourceString = '/home/user/directory/'; $secondString = '/home/user/directory/subdirecotry/filename'; $result = Str::differenceSubstring($sourceString, $secondString); // Output: 'subdirecotry/filename';
以下是一个示例,其中确定两个不同字符串的差异。由于字符串不同,所以函数的结果将是null。
$sourceString = '/home/user/'; $secondString = '/user/directory/subdirecotry/filename'; $result = Str::differenceSubstring($sourceString, $secondString); // Output: null
如果其中一个值是空字符串,则函数的结果将是填充的字符串。而比较相同的字符串将返回空字符串。
$sourceString = ''; $secondString = '/home/user/directory/subdirecotry/filename'; $result = Str::differenceSubstring($sourceString, $secondString); // Output: '/home/user/directory/subdirecotry/filename'
Str::findPositionFromEnd
Str::findPositionFromEnd($haystack, $needle, $offset = 0, $fromEnd = false)
该函数返回子字符串的起始位置。搜索从字符串末尾开始。如果未找到子字符串,则返回false。默认返回的位置从字符串开头开始计数,但可以更改此值以返回从字符串末尾开始计数的位置,从-1开始,并更深入。与函数strpos()
和mb_strpos()
不同,此函数的搜索是从字符串末尾开始的,而不是从开头。
函数参数
- $haystack - 原始字符串;
- $needle - 要搜索的值(符号或字符串);
- $offset - 从字符串末尾开始的搜索起始位置偏移量;
- $fromEnd - 如果true,则返回从末尾开始计数的位置(值-1 - 最后一个元素)。
让我们看看这个函数的工作示例。
$string = "Lorem ipsum dolor sit amet... dolore magna aliqua."; # Example 1: Поиск значения без дополнительных параметров $result = Str::findPositionFromEnd($string, "dolor"); // Output: 30 # Example 2: Поиск значения без отступа от конца строки, а возвращаемая позиция должна отсчитываться с конца строки с позиции '-1'. $result = Str::findPositionFromEnd($string, "dolor", 0, true); // Output: -20 # Example 3: Поиск значения с отступом с конца в 20 символов. $result = Str::findPositionFromEnd($string, "dolor", 20); // Output: 12 # Example 4: Поиск значения с отступом с конца в 20 символов и возврат значения с отчетом с конца строки. $result = Str::findPositionFromEnd($string, "dolor", 20, true); // Output: -38 # Example 5: Поиск одного символа $result = Str::findPositionFromEnd($string, "."); // Output: 49 # Example 6: Поиск одного символа с конца строки и возврат значения с отчетом с конца строки. $result = Str::findPositionFromEnd($string, ".", 0, true); // Output: -1 # Example 7: Поиск несуществующего символа $result = Str::findPositionFromEnd($string, "!"); // Output: null
如果您需要从末尾开始计数(而不是从-1开始),以获得字符串末尾的值,请使用以下示例。
$string = "Lorem ipsum dolor sit amet... dolore magna aliqua."; $result = Str::findPositionFromEnd($string, "dolor", 0, true); $result = ($result + 1) * (-1); // 19 // or $result = abs($result + 1); // 19
Str::firstElementOfChain
Str::firstElementOfChain($chain, $separator = '.', $strict = false)
返回指定链的第一个元素。
函数参数
- $chain - 通过分隔符连接的值组成的字符串(值链),例如,'path.to.file'或'/path/to/file'或'/path/to/directory/';
- $separator - 单个字符或字符串分隔符;
- $strict - 严格模式。在严格模式下,返回分隔符左侧的第一个结果。
让我们看看这个函数的工作示例。函数的结果取决于其参数,当然,我们指的是strict参数。
在第一个示例中,我们处理由点分隔的值链。这类字符串用于Laravel的配置访问、Blade模板连接、数组元素访问和其他数据。点(`.`)是默认分隔符,因为它是处理链的最简单方式。
$chain = "path.to.file"; $result = Str::firstElementOfChain($chain); // Output: 'path'
如果您不希望使用点,您可以设置任何其他分隔符,例如单个字符甚至字符串。
在下面的示例中,我们使用斜杠('/'),它可以用于分隔文件或目录的路径。
$chain = "/path/to/file"; $result = Str::firstElementOfChain($chain); // Output: 'path'
在不严格模式下,我们始终返回第一个“有效”值,即不同于分隔符的值。但有时我们可能需要获取链的实际第一个值,即使它可能是“不正确的”。
让我们比较不同模式下函数的工作,包括使用不正确值的情况。
// Example 1 $chain = "path.to.file"; $nonStrict = Str::firstElementOfChain($chain, '.'); // Output: 'path' $strict = Str::firstElementOfChain($chain, '.', true); // Output: 'path' // Example 2 $chain = "/path/to/file"; $nonStrict = Str::firstElementOfChain($chain, '/'); // Output: 'path' $strict = Str::firstElementOfChain($chain, '/', true); // Output: null // Example 3 $chain = "////path/to/file"; $nonStrict = Str::firstElementOfChain($chain, '/'); // Output: 'path' $strict = Str::firstElementOfChain($chain, '/', true); // Output: null // Example 4 $chain = "path"; $nonStrict = Str::firstElementOfChain($chain, '/'); // Output: 'path' $strict = Str::firstElementOfChain($chain, '/', true); // Output: 'path' // Example 5 $chain = "==path==to==file"; $nonStrict = Str::firstElementOfChain($chain, '=='); // Output: 'path' $strict = Str::firstElementOfChain($chain, '==', true); // Output: null // Example 6 $chain = "path====to====file"; $nonStrict = Str::firstElementOfChain($chain, '=='); // Output: 'path' $strict = Str::firstElementOfChain($chain, '==', true); // Output: 'path' // Example 7 $chain = "===path==to==file"; $nonStrict = Str::firstElementOfChain($chain, '=='); // Output: '=path'
如所示,使用正确数据时,函数的结果容易预测。但在示例7中,注意使用多字符分隔符时结果。
Str::lastElementOfChain
Str::lastElementOfChain($chain, $separator = '.', $strict = false)
返回指定链的最后一个元素。这个函数与firstElementOfChain()
函数相反。
函数参数
- $chain - 通过分隔符连接的值组成的字符串(值链),例如,'path.to.file'或'/path/to/file'或'/path/to/directory/';
- $separator - 单个字符或字符串分隔符;
- $strict - 严格模式。在严格模式下,返回分隔符右侧的第一个结果。
这个函数的工作原理与上一个函数相同:设置字符串、分隔符和,如果需要,工作模式。
$chain = 'path.to.element'; $element = Str::lastElementOfChain($chain); // Output: 'element' $chain = 'path/to/element'; $element = Str::lastElementOfChain($chain, '/'); // Output: 'element' $chain = 'path/to/element/'; $element = Str::lastElementOfChain($chain, '/'); // Output: 'element' $chain = 'path/to/element/'; $element = Str::lastElementOfChain($chain, '/', true); // Output: null $chain = 'path/to/element////'; $element = Str::lastElementOfChain($chain, '/'); // Output: 'element'
请注意多字符分隔符的工作方式!当使用链的多字符分隔符时,分隔符的多个字符被计为一个字符集。下面是如何使用这些分隔符的示例。
# Example 1 $chain = '==path==to==any==object==='; $element = Str::lastElementOfChain($chain, '==', true); // Output: null # Example 2 $chain = '==path==to==any==object==='; $element = Str::lastElementOfChain($chain, '=='); // Output: 'object='
在第二个示例中,您可以看到函数的结果不是object,而是object=。这是因为最后一个分隔符被计为一个字符,然后发生了移动(这是2个字符)。在使用多字符分隔符时要考虑这一点。
ServiceProvider (取决于Laravel: Illuminate\Support\ServiceProvider, Illuminate\Foundation\AliasLoader)
Belca\Support\ServiceProvider类扩展了Illuminate\Support\ServiceProvider类。它向类添加了新功能。
recurciveReplaceConfigFrom
recurciveReplaceConfigFrom($path, $key)
递归替换并扩展配置值。与Laravel内置的mergeConfigFrom()
函数不同,当前函数替换嵌套数组中的最终值并补充新元素到数组中,而不是完全重写主要键的值。
函数参数
- $path - 配置路径(返回数组的PHP文件)。
- $key - 要替换的配置数组的关联键。
函数调用方式与mergeConfigFrom()
相同。
// $this->mergeConfigFrom(__DIR__.'/../config/page.php', 'page'); // default in Laravel $this->recurciveReplaceConfigFrom(__DIR__.'/../config/page.php', 'page');
让我们比较一下函数执行的结果。
$source = [ 'one' => [ 'one_one' => 1, 'one_two' => 2, 'one_three' => 3, ], 'two' => [ 'two_one' => 1, 'two_two' => 2, 'two_three' => 3, ], ]; $newConfig = [ 'one' => [ 'one_one' => 10, 'one_two' => 20, 'one_three' => 30, ], 'two' => [ 'two_two' => 20, 'two_four' => 40, ], 'three' => [ 'three_one' => 30, ], ]; // The result of merge by Laravel // [ // 'one' => [ // 'one_one' => 10, // 'one_two' => 20, // 'one_three' => 30, // ], // 'two' => [ // // the old values are not left // 'two_two' => 20, // 'two_four' => 40, // ], // 'three' => [ // 'three_one' => 30, // ], // ] // The result of merge by the new function // [ // 'one' => [ // 'one_one' => 10, // 'one_two' => 20, // 'one_three' => 30, // ], // 'two' => [ // 'two_one' => 1, // it is left // 'two_two' => 20, // 'two_three' => 3, // it is left // 'two_four' => 40, // ], // 'three' => [ // 'three_one' => 30, // ], // ]
如你所见,结果有所不同。当需要用新值替换或部分补充旧配置时,这个函数非常方便使用。
这个函数最常用于向嵌套数组的值中添加新值。