Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string after 1 or more occurrences of the same character

Tags:

string

php

split

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?

like image 445
Vecta Avatar asked Jan 20 '26 19:01

Vecta


1 Answers

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
)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!