Link to home
Start Free TrialLog in
Avatar of amiller177
amiller177

asked on

parse string

I am trying to convert a long string of characters into an array, split by character groups.

For example, from the string "AAABCCCCDDAAAAEEE", I need separate strings "AAA" "B" "CCCC" "DD" "AAAA" "EEE"

Thanks for your help.
ASKER CERTIFIED SOLUTION
Avatar of VGR
VGR

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of VGR
VGR

it misses the last character
add $string[$i-1] to $elements[$j] before doing $j++ at the end of the loop

sorry, wrote this in one shot
Avatar of amiller177

ASKER

VGR,

Little change was needed to produce the required results:
$oldchar=$string[0];
$curchar=$string[$i+1];
no j++ after loop finishes, as follows:


<?
$string="AAABCCCCDDAAAAEEE";
$elements=array();

$i=0; // counter of chars
$j=0; // counter of elements
$oldchar=$string[0];

while ($i<strlen($string)) {
  $curchar=$string[$i+1];
  if ($curchar<>$oldchar) { // add found string before continuing
    $elements[$j].=$oldchar;
    $oldchar=$curchar;
    $j++;
    }
  else $elements[$j].=$curchar; // if we broke sequence
  $i++;
  } // while string not parsed completely
for ($i=0; $i<$j;$i++) echo "element $i = '".$elements[$i]."'<BR>";
?>