Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge string with common middle part

Tags:

string

php

I have two strings:

$a = '/srv/http/projects/name';
$b = '/projects/name/some/dir';

And I would like to get a merged string with not repeated common part:

$c = '/srv/http/projects/name/some/dir';

Is there any effective way to get it ?

like image 283
hsz Avatar asked Dec 21 '25 04:12

hsz


2 Answers

Nothing that I know of out-of-the-box. but this should do it:

function merge_overlap($left, $right) {
  // continue checking larger portions of $right
  for($l = 1; $l < strlen($right); $l++) {
    // if we no longer have a matching subsection return what's left appended
    if(strpos($left, substr($right, 0, $l)) === false) {
      return $left . substr($right, $l - 1);
    }
  }

  // no overlap, return all
  return $left . $right;
}

EDIT: Had an OBO, updated.

UPDATE: That was not the solution, strpos() is matching portions of text anywhere in the left path, should compare against tail.

Here is the correct implementation for my approach:

function merge_overlap($left, $right) {
  $l = strlen($right);
  // keep checking smaller portions of right
  while($l > 0 && substr($left, $l * -1) != substr($right, 0, $l))
    $l--;

  return $left . substr($right, $l);
}
like image 184
nortron Avatar answered Dec 22 '25 20:12

nortron


It's kinda ugly, and assumes your strings always start with '/'... but:

$a = '/srv/http/projects/name';
$b = '/projects/name/some/dir';

$merged = array_merge(explode('/', $a), explode('/', $b) );
$unique = array_unique($merged);

$c = implode('/', $unique);

print $c; // prints "/srv/http/projects/name/some/dir"
like image 42
Owen Avatar answered Dec 22 '25 18:12

Owen