[英]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.