php从文件集中提取根目录

时间:2011-11-02 20:10:38

标签: 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中用最少的痛苦找到并删除它?

2 个答案:

答案 0 :(得分:1)

<?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;

答案 1 :(得分:0)

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

点击此处了解详情:http://php.net/manual/en/function.str-replace.php