php - 合并具有公共(public)中间部分的字符串

标签 php string

我有两个字符串:

$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/

相关文章:

java - 如何检查字符串是否等于有效字符之一? (棋盘)

ios - 如何使用 Swift 在文本字段(从右到左)输入货币格式?

php - Laravel 5.1 任务调度命令问题

php - 将唯一字符串转换为时间戳

php - 如何减少 PHP 代码?

python - 如何使用索引替换列值的前两个字母

java - 简单的JAVA问题。但对我来说很难

php - 优化 mod_rewrite

Javascript 变量值到 php 变量

java - 发送文本或按键到外部程序