简体   繁体   中英

php extract root directory from set of files

I have a filelist:

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

its obvious that "C:/PATH/PATH2/" is the root of them. How to find and remove it with the least pain in php?

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

If you just want to remove the C:/PATH/PATH2 from a string, use: str_replace

See more about it here: http://php.net/manual/en/function.str-replace.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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