3

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.

TIA

Alix Axel
  • 147,060
  • 89
  • 388
  • 491
Jamex
  • 79
  • 6
  • It's a problem to find the largest common substring: http://stackoverflow.com/questions/336605/how-can-i-find-the-largest-common-substring-between-two-strings-in-php – diyism May 18 '12 at 03:00

3 Answers3

6

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" )
Dieter Gribnitz
  • 4,642
  • 2
  • 38
  • 36
  • +1 I would change `$s1 = substr($str1, $sl1-$i);` to: `$s1 = substr($str1, -$i);` - it would be more elegant ;) second, you might want to consider also checking overlap in the opposite direction: `findOverlap($str2, $str1);` – Nir Alfasi Dec 20 '12 at 08:17
  • Was looking for something like this for a bit. Great solution! Thank you. – HartleySan Dec 28 '18 at 11:59
-1

No, there is no builtin function, but you can easily write one yourself by using substr and a loop to see how much of the strings that overlap.

Emil Vikström
  • 87,715
  • 15
  • 134
  • 170
  • Thanks, I am just looking for a short cut to cut down on the code. But I guess it is not possible. – Jamex May 31 '10 at 19:18
-1

It's possible using substr_replace() and strcspn():

$string1 = 'abcde';
$string2 = 'cdefgh';

echo substr_replace($string1, $string2, strcspn($string1, $string2)); // abcdefgh
Alix Axel
  • 147,060
  • 89
  • 388
  • 491