sashabo/iterable-string

IterableString 和 MultibyteIterableString 允许在 foreach 中迭代字符串字符,而无需将字符串转换为数组。

1.1 2023-10-21 14:54 UTC

This package is auto-updated.

Last update: 2024-09-05 11:06:08 UTC


README

PHP 库,允许在 foreach 中迭代字符串字符,而无需将字符串转换为数组。

IterableString

foreach (new IterableString('lorem ipsum') as $position => $char) {
    echo $position.'['.$char.'] ';
}

$iterableString = new IterableString('lorem ipsum');
while ($iterableString->valid()) {
    echo $iterableString->key().'['.$iterableString->current().'] ';
    $iterableString->next();
}

打印 0[l] 1[o] 2[r] 3[e] 4[m] 5[ ] 6[i] 7[p] 8[s] 9[u] 10[m]

MultibyteIterableString

功能相同,但使用 mb_* 函数,因此可以正确处理 UTF-8。

foreach (new MultibyteIterableString('visgaršīgākie āboli Rīgā') as $position => $char) {
    echo $position.'['.$char.'] ';
}

打印 0[v] 1[i] 2[s] 3[g] 4[a] 5[r] 6[š] 7[ī] 8[g] 9[ā] 10[k] 11[i] 12[e] 13[ ] 14[ā] 15[b] 16[o] 17[l] 18[i] 19[ ] 20[R] 21[ī] 22[g] 23[ā]

方法

rewind(): void - 设置位置为 0(在 foreach 开始时自动调用)

current(int $length = 1): string - 当前字符

next(int $steps = 1): void - 增加位置

previous(int $steps = 1): void - 减少位置

key(): int - 当前位置

valid(): bool - 当前位置不是小于 0 或大于源字符串长度

check(int $position): bool - 对任何位置都相同

isLast(): bool - 如果当前字符是源字符串中的最后一个,则为 true

length(): int - 源字符串的长度(strlen 或 mb_strlen)

set(int $position): void - 设置位置

get(int $position, int $length = 1): string - 返回一个字符或几个字符

安装

composer require sashabo/iterable-string