php从一组文件中提取根目录

php从一组文件中提取根目录,php,filesystems,Php,Filesystems,我有一个文件列表: C:/PATH/PATH2/file1.txt C:/PATH/PATH2/file2.txt C:/PATH/PATH2/file3.txt C:/PATH/PATH2/fs/file4.txt C:/PATH/PATH2/fs/xfile5.txt C:/PATH/PATH2/x/file6.txt 很明显,“C:/PATH/PATH2/”是它们的根。如何在php中以最轻松的方式查找和删除它?如果您只想从字符串中删除C:/PATH/PATH2,请使用:str\u rep

我有一个文件列表:

C:/PATH/PATH2/file1.txt
C:/PATH/PATH2/file2.txt
C:/PATH/PATH2/file3.txt
C:/PATH/PATH2/fs/file4.txt
C:/PATH/PATH2/fs/xfile5.txt
C:/PATH/PATH2/x/file6.txt

很明显,“C:/PATH/PATH2/”是它们的根。如何在php中以最轻松的方式查找和删除它?

如果您只想从字符串中删除C:/PATH/PATH2,请使用:str\u replace


请在此处查看更多信息:

可能重复@user查看我的重复链接。有很多解决方案,你可以从字符串的右边开始搜索第一个“/”右边的所有内容都是文件名,左边的所有内容都是路径。
<?php

$files = array(
  'C:/PATH/PATH2/file1.txt',
  'C:/PATH/PATH2/file2.txt',
  'C:/PATH/PATH2/file3.txt',
  'C:/PATH/PATH2/fs/file4.txt',
  'C:/PATH/PATH2/fs/xfile5.txt',
  'C:/PATH/PATH2/x/file6.txt',
);

foreach ($files as $file) {
  // use the first file as the base
  if (!isset($base)) {
    $base = $file;
    continue;
  }

  // use the shortest of the base and the current file as the loop limit
  $length = strlen($base) < strlen($file) ? strlen($base) : strlen($file);

  // compare each character of the two starting from the beginning
  for($i = 0;$i<$length;$i++) {
    // stop when characters don't match
    if ($base[$i] !== $file[$i]) {
      break;
    }
  }

  // set the base to the matching characters
  $base = substr($base, 0, $i);
}

// strip the last slash and any file/subdir characters that happened to also match
$base = substr($base, 0, strrpos($base, '/'));
echo 'base ', $base, PHP_EOL;