Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

built in function to combine overlapping string sequences in php?

Is there a built in function in PHP that would combine 2 strings into 1?

Example:

$string1 = 'abcde';
$string2 = 'cdefg';

Combine to get: abcdefg.

If the exact overlapping sequence and the position are known, then it is possible to write a code to merge them.

like image 762
Jamex Avatar asked Apr 14 '26 16:04

Jamex


1 Answers

I found the substr_replace method to return funny results. Especially when working with url strings. I just wrote this function. It seems to be working perfectly for my needs. The function will return the longest possible match by default.

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" )
like image 96
Dieter Gribnitz Avatar answered Apr 17 '26 06:04

Dieter Gribnitz