Php 无法操作readdir()函数中的字符串

Php 无法操作readdir()函数中的字符串,php,Php,下面我有两个函数 function ListFiles($dir) { if($dh = opendir($dir)) { $files = array(); $topics = array(); $inner_files = array(); while($file = readdir($dh)) { if($file != "." && $file != ".." &&am

下面我有两个函数

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()方法中的字符串。但是如果我放一个纯字符串,结果是正确的。请检查代码是否清楚

我要做的是获取文件路径,将其父文件夹另存为主题


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

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

1-在函数getTopicFromPath()中,如果string3为NULL,则在string2中找不到“/”。 也许你在Windows下,你的目录分隔符是“\”而不是“/”

要解决这些问题,请使用本机目录分隔符常量

2-显然,此函数尝试查找文件$path的目录名。 然后,您最好使用与目录相关的函数,并避免过于具体的编码。 过于具体往往意味着上下文相关且脆弱

不管怎样,我已经将你的函数改写为两行,两种风格:

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

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

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

4-最后,您应该清理ListFile()函数:

closedir($dh);
$topics = array();
$i = 0;
$topics=array()
意味着上述分配到此变量中是无用的,因为它们将被重载


$i
在其范围内未使用

呃。。。你能告诉我问题是什么吗?
如果($file!=”&&&$file!=”。&&&&$file[0]!=”)
可以是
如果($file[0]!=”)
为什么不那么老,使用glob()mandefine“无法操作”很抱歉我没有清理它,因为我还在做一些测试谢谢你的建议:)
closedir($dh);
$topics = array();
$i = 0;