Click to See Complete Forum and Search --> : group similar data in a string?
ktsirig
04-25-2008, 05:20 PM
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.
andre4s_y
04-28-2008, 08:47 AM
Very challenging.. :p
<?php
$text = "-----MMMMM------IIIII----MMM---OOOO---I---MMMM-----";
$text = str_split($text);
$pattern = "#[IMO]#";
$count = count($text);
$result = "";
for ($i = 0; $i < $count; $i++)
{
if(!preg_match($pattern,$text[$i]))
unset($text[$i]);
}
reset($text);
$i = 0;
do {
$pos = key($text);
$current = current($text);
$key_next = $pos + 1;
if ($current == next($text))
{
$key_next = $pos + 1;
if($key_next==key($text))
{
$i++;
prev($text);
}
else
{
if($pos!=0)
{
$first = $pos + 1 - $i;
$i = 0;
$end = $pos +1;
$prev = prev($text);
if(empty($prev))
{
$prev = end($text);
}
if($first==$end)
{
$result .= $first.":".$prev."<br />\n\r";
}
else
{
$result .= $first."-".$end.":".$prev."<br />\n\r";
}
}
}
}
else
{
$first = $pos + 1 - $i;
$i = 0;
$end = $pos +1;
$prev = prev($text);
if(empty($prev))
{
$prev = end($text);
}
if($first==$end)
{
$result .= $first.":".$prev."<br />\n\r";
}
else
{
$result .= $first."-".$end.":".$prev."<br />\n\r";
}
}
next($text);
}while($pos!=key($text));
echo $result;
?>
it will output :
6-10:M
17-21:I
26-28:M
32-35:O
39:I
43-46:M
Whew...
This code maybe not the short one, but it answer the problem...
[RESOLVED].. :D