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 ?
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);
}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With