我有两个字符串:
$a = '/srv/http/projects/name';
$b = '/projects/name/some/dir';
我想得到一个没有重复公共(public)部分的合并字符串:
$c = '/srv/http/projects/name/some/dir';
有什么有效的方法可以得到吗?
最佳答案
据我所知,开箱即用。 但应该这样做:
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;
}
编辑:有一个 OBO,已更新。
更新:这不是解决方案,strpos() 正在匹配左侧路径中任意位置的文本部分,应该与 tail 进行比较。
这是我的方法的正确实现:
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);
}
关于php - 合并具有公共(public)中间部分的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2267074/