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
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.

Link to comment
Share on other sites

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


 

 

Link to comment
Share on other sites

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

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.