readdir()函数中的字符串不能被操作


String from readdir() function cannot be manipulate

下面有两个函数

function ListFiles($dir) {
    if($dh = opendir($dir)) {
        $files = array();
        $topics = array();
        $inner_files = array();
        while($file = readdir($dh)) {
            if($file != "." && $file != ".." && $file[0] != '.') {
                array_push($topics, $file);
                if(is_dir($dir . "/" . $file)) {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files);
                } else {
                    array_push($files, $dir . "/" . $file);
                }
            }
        }
        closedir($dh);
        $topics = array();
        $i = 0;
        foreach ($files as $file) {
//wrong result
            $topics[] = getTopicFromPath($file);
//correct result
//$topics[] = getTopicFromPath("/Users/Unknown/Sites/sample/training/topic/acq/19ddb673359747ee9095.txt")
        }
        return $topics;
    }
}
function getTopicFromPath($path){
//$path = /Users/Unknown/Sites/sample/training/topic/acq/19ddb673359747ee9095.txt
    $string1 = substr($path,strpos($path,"topic/"));
//$string1 = topic/acq/19ddb673359747ee9095.txt
    $string2 = str_replace("topic/", "", $string1);
//$string2  = acq/19ddb673359747ee9095.txt
    $string3 = strstr($string2, '/', true);
//$string3 = null
//expecting $string3 = 'acq'
    return $string3;;
}

问题是getTopicFromPath($path)不能从readdir()方法解析字符串。但如果我放一个纯字符串,结果是正确的。请检查代码是否清楚

我要做的是获取文件路径,将其父文件夹保存为topic。

使用另一种方法获取文件可能会解决这个问题。但我很好奇这些函数有什么问题?

主要问题是您的代码需要清理和简化。

1 -在你的函数getTopicFromPath()中,如果string3是NULL,那么'/'没有在string2中找到。也许你在Windows下,你的目录分隔符是"'"而不是"/"?

要解决这些问题,可以使用本地DIRECTORY_SEPARATOR常量。

2 -显然,这个函数试图找到你的文件$path的目录名。那么最好使用与目录相关的函数,避免过于具体的编码。过于具体往往意味着依赖于上下文和脆弱。

无论如何,我将把你的函数重写为两行,两种风格:

function getTopicFromPath($path) {
    $dir = dirname($path);
    return substr($dir, strrpos($dir, DIRECTORY_SEPARATOR) + 1);
}

function getTopicFromPath($path) {
    $dir = dirname($path);
    return basename($dir);
}

3 - getTopicFromPath()在递归函数中被调用。许多条目将被处理多次。这是多余的。

您应该将您的过程分为两个独立的步骤:首先检索文件的完整路径,然后修剪它们。您将获得可重用性和健壮性。

最后,您应该清理ListFile()函数:
closedir($dh);
$topics = array();
$i = 0;

$topics = array()意味着上述对该变量的赋值是无用的,因为它们将被重载。

$i在其作用域中未使用。