Convert string to array with different character

I have this string 'aaaabbbaaaaaabbbb'

I want to convert this to an array to get the following result

$array = [
    'aaaa',
    'bbb',
    'aaaaaa',
    'bbbb'   
]

      

How do I do this in PHP?

+3


source to share


2 answers


I wrote one liner using only preg_split () that generates the expected result without wasting memory (no bloating the array):

Code ( Demo ):

$string='aaaabbbaaaaaabbbb';
var_export(preg_split('/(.)\1*\K/',$string,NULL,PREG_SPLIT_NO_EMPTY));

      

Output:

array (
  0 => 'aaaa',
  1 => 'bbb',
  2 => 'aaaaaa',
  3 => 'bbbb',
)

      

template:

(.)         #match any single character
\1*         #match the same character zero or more times
\K          #keep what is matched so far out of the overall regex match

      

Real magic happens to \K

, go here for more reading . Parameter NULL

in preg_split()

means "unlimited match". This is the default behavior, but it must hold its place in the function for the next parameter to be used appropriately as the flag

End parameter is PREG_SPLIT_NO_EMPTY

, which removes any empty matches.




Sahil's preg_match_all () method preg_match_all('/(.)\1{1,}/', $string,$matches);

is a good try, but it's not perfect for two reasons:

The first problem is that using it preg_match_all()

returns two subarrays that double the desired result.

The second problem arises when $string="abbbaaaaaabbbb";

. His method ignores the first character. Here's his output:

Array (
    [0] => Array
        (
            [0] => bbb
            [1] => aaaaaa
            [2] => bbbb
        )
    [1] => Array
        (
            [0] => b
            [1] => a
            [2] => b
        )
)

      

Sahil's second attempt produces correct output, but requires a lot more code. A more concise solution without regular expressions might look like this:

$array=str_split($string);
$last="";
foreach($array as $v){
    if(!$last || strpos($last,$v)!==false){
        $last.=$v;
    }else{
        $result[]=$last;
        $last=$v;
    }
}
$result[]=$last;
var_export($result);

      

0


source


PHP demo

Regex: (.)\1{1,}

(.)

: match and capture a single character.

\1

: this will be the first match

\1{1,}

: Use the matching character one or more times.

<?php
ini_set("display_errors", 1);
$string="aaaabbbaaaaaabbbb";
preg_match_all('/(.)\1{1,}/', $string,$matches);
print_r($matches);

      

Output:



Array
(
    [0] => Array
        (
            [0] => aaaa
            [1] => bbb
            [2] => aaaaaa
            [3] => bbbb
        )

[1] => Array
    (
        [0] => a
        [1] => b
        [2] => a
        [3] => b
    )

)

      

Or:

PHP demo

<?php
$string="aaaabbbaaaaaabbbb";
$array=str_split($string);
$start=0;
$end=  strlen($string);
$indexValue=$array[0];
$result=array();
$resultantArray=array();
while($start!=$end)
{
    if($indexValue==$array[$start])
    {
        $result[]=$array[$start];
    }
    else
    {
        $resultantArray[]=implode("", $result);
        $result=array();

        $result[]=$indexValue=$array[$start];
    }
    $start++;
}
$resultantArray[]=implode("", $result);
print_r($resultantArray);

      

Output:



Array
(
    [0] => aaaa
    [1] => bbb
    [2] => aaaaaa
    [3] => bbbb
)

      

+5


source







All Articles