繁体   English   中英

PHP从文件集提取根目录

[英]php extract root directory from set of files

我有一个文件列表:

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

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

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

在此处查看有关此内容的更多信息: http : //php.net/manual/en/function.str-replace.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM