Jump to content

group similar data in a string?


ktsirig

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/102962-group-similar-data-in-a-string/
Share on other sites

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.

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);
    
?>


 

 

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);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.