I don't think there's a "smart" way to do that. Just iterate over $a
until all of the rightmost tokens match the same number of tokens at the beginning of $b
.
Here I explode()
both strings so that I can easily capture the right number of tokens via array_slice()
.
$a = '/srv/http/projects/name/http';
$b = '/projects/name/http/some/dir';
var_dump(merge_path($a, $b));
function merge_path($path1, $path2)
{
$p1 = explode('/', trim($path1,' /'));
$p2 = explode('/', trim($path2,' /'));
$len = count($p1);
do
{
if (array_slice($p1, -$len) === array_slice($p2, 0, $len))
{
return '/'
. implode('/', array_slice($p1, 0, -$len))
. '/'
. implode('/', $p2);
}
}
while (--$len);
return false;
}