在同一字符出现 1 次或多次后拆分字符串

发布于 2024-11-18 06:59:52 字数 227 浏览 2 评论 0原文

我无法弄清楚如何将字符串拆分为相同字符的组。我有一些与此类似的相当随机的字符组字符串:

$string = 'aaabb2222eee77777';

我希望能够像这样分割它们:

['aaa', 'bb', '2222', 'eee', '77777']

然后能够计算每组中的字符数。做到这一点最简单的方法是什么?

I'm having trouble figuring out how to split a string into groups of identical characters. I have a few strings of rather random character groups similar to this one:

$string = 'aaabb2222eee77777';

I would like to be able to split them like so:

['aaa', 'bb', '2222', 'eee', '77777']

and then be able to count the number of characters in each set. What would be the easiest way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

渔村楼浪 2024-11-25 06:59:52

然后,您可以迭代该数组并获取每个项目的 strlen()

preg_match_all('/(.)\1*/', 'aaabb2222eee77777', $matches);
$matches = $matches[0];
Array
(
   [0] => aaa
   [1] => bb
   [2] => 2222
   [3] => eee
   [4] => 77777
)

You can then iterate through the array and get the strlen() of each item:

preg_match_all('/(.)\1*/', 'aaabb2222eee77777', $matches);
$matches = $matches[0];
Array
(
   [0] => aaa
   [1] => bb
   [2] => 2222
   [3] => eee
   [4] => 77777
)
愿得七秒忆 2024-11-25 06:59:52

如果您不想声明新的引用变量来保存结果数组,或者不想填充二维数组,或者更喜欢直接返回所需的平面结果数组,请使用 preg_split() 而不是 preg_match_all()

捕获任意一个字符,然后匹配该字符的零个或多个后续副本,然后用 \K 忘记这些字符——这将允许该函数在每个重复序列之后在零宽度位置上进行分割人物。

代码:(Demo)

$string = 'aaabb2222eee77777';

var_export(
    preg_split('/(.)\1*\K/', $string, flags: PREG_SPLIT_NO_EMPTY)
);

array (
  0 => 'aaa',
  1 => 'bb',
  2 => '2222',
  3 => 'eee',
  4 => '77777',
)

要查找每个元素的长度,只需使用 strlen() 循环调用。 (演示

$array = preg_split('/(.)\1*\K/', $string, flags: PREG_SPLIT_NO_EMPTY);
$counts = array_map(strlen(...), $array);
var_dump($array, $counts);

If you don't want to declare a new reference variable to hold the result array, or don't want to populate a 2d array, or prefer to directly return the desired flat result array, then use preg_split() instead of preg_match_all().

Capture any one character, then match zero or more subsequent copies of that character, then forget those characters with \K -- this will allow the function to split on the zero-width position after each sequence of repeated characters.

Code: (Demo)

$string = 'aaabb2222eee77777';

var_export(
    preg_split('/(.)\1*\K/', $string, flags: PREG_SPLIT_NO_EMPTY)
);

array (
  0 => 'aaa',
  1 => 'bb',
  2 => '2222',
  3 => 'eee',
  4 => '77777',
)

To find the lengths of each element, just make strlen() calls in a loop. (Demo)

$array = preg_split('/(.)\1*\K/', $string, flags: PREG_SPLIT_NO_EMPTY);
$counts = array_map(strlen(...), $array);
var_dump($array, $counts);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文