ktsirig Posted April 25, 2008 Share Posted April 25, 2008 Hello all I didn't know a good way of naming my question, so I am getting straight to the point: I have a string like the following: -----MMMMM------IIIII----MMM---OOOO---I---MMMM----- Is there any way I can gather and group my information and get, for example: 6-10:M 17-21:I 26-28:M 32-35:O 39:I 43-46:M Thank you in advance. Quote Link to comment https://forums.phpfreaks.com/topic/102962-group-similar-data-in-a-string/ Share on other sites More sharing options...
dptr1988 Posted April 25, 2008 Share Posted April 25, 2008 Yes, but I don't know of any PHP function that would do it, so you would need to make your own. Here's how I'd do it. Skip over the string untill you find anything but the '-' char. Save that char that you just found in a variable, and then keep on searching untill you find something other then that char from the variable. Store the new char in the variable and repeat untill the end of the string. Quote Link to comment https://forums.phpfreaks.com/topic/102962-group-similar-data-in-a-string/#findComment-527450 Share on other sites More sharing options...
dptr1988 Posted April 25, 2008 Share Posted April 25, 2008 Here is an example: <?php $input = "-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----"; $trash_char = '-'; $results = array(); $current_char = false; $a_index = 0; for( $i =0; $i < strlen($input); $i++) { if ($input[$i] != $trash_char AND $current_char === false) { // We are in a new group $current_char = $input[$i]; $results[$a_index]['start'] = $i; } elseif ( $current_char !== false AND ( ($input[$i] != $current_char) OR ($i+1 >= strlen($input) ) ) ) { // We are at the end of the group $results[$a_index]['end'] = $i - 1; $results[$a_index]['char'] = $current_char; $current_char = false; $a_index++; } // else skip over that char } print_r($results); ?> Quote Link to comment https://forums.phpfreaks.com/topic/102962-group-similar-data-in-a-string/#findComment-527456 Share on other sites More sharing options...
sasa Posted April 26, 2008 Share Posted April 26, 2008 try <?php $input = "-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----"; $trash_char = '-'; $results = array(); //$current_char = false; //$a_index = 0; for( $i =0; $i < strlen($input){ if ($input[$i] != $trash_char){ $char = $input[$i]; $start = $i + 1; while ($input[$i] == $char) $i++; $end = $i > $start ? '-'.$i : ''; $results[] = $start.$end.':'.$char; } else $i++; } print_r($results); ?> Quote Link to comment https://forums.phpfreaks.com/topic/102962-group-similar-data-in-a-string/#findComment-527586 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.