kisabelle
5/6/2014 - 10:22 PM

Combine Overlapping Strings

Combine Overlapping Strings


/*----------------------------------------------*/
/*  Combine Overlapping Strings
/*----------------------------------------------*/

function findOverlap($str1, $str2){
  $return = array();
  $sl1 = strlen($str1);
  $sl2 = strlen($str2);
  $max = $sl1>$sl2?$sl2:$sl1;
  $i=1;
  while($i<=$max){
    $s1 = substr($str1, -$i);
    $s2 = substr($str2, 0, $i);
    if($s1 == $s2){
      $return[] = $s1;
    }
    $i++;
  }
  if(!empty($return)){
    return $return;
  }
  return false;
}

function replaceOverlap($str1, $str2, $length = "long"){
  if($overlap = findOverlap($str1, $str2)){
    switch($length){
      case "short":
        $overlap = $overlap[0];
        break;
      case "long":
      default:
        $overlap = $overlap[count($overlap)-1];
        break;
    }     
    $str1 = substr($str1, 0, -strlen($overlap));
    $str2 = substr($str2, strlen($overlap));
    return $str1.$overlap.$str2;
  }
  return false;
}

/* 
  Usage to get the maximum length match:

  echo replaceOverlap("abxcdex", "xcdexfg"); //Result: abxcdexfg
  To get the first match instead of the last match call the function like this:

  echo replaceOverlap("abxcdex", "xcdexfg", “short”); //Result: abxcdexcdexfg
  To get the overlapping string just call:

  echo findOverlap("abxcdex", "xcdexfg"); //Result: array( 0 => "x", 1 => "xcdex" )
*/

// Source:
// http://stackoverflow.com/questions/2945446/built-in-function-to-combine-overlapping-string-sequences-in-php

//----------------------------------------------/