从父目录

时间:2016-03-25 01:53:57

标签: php wordpress function loops oop

我试图想出一种搜索父目录内所有* .php文件的方法,父目录示例:

  

/内容/主题/默认/

我不想搜索子目录中的所有文件。我想要搜索嵌入在PHP注释语法中的字符串,例如:

/* Name: default */

如果找到变量,则获取文件名和/或路径。我试过谷歌搜索,并考虑自定义的方法,这是我迄今为止尝试过的:

public function build_active_theme() {
    $dir = CONTENT_DIR . 'themes/' . $this->get_active_theme() . '/';

    $theme_files = array();
    foreach(glob($dir . '*.php') as $file) {
        $theme_files[] = $file;
    }

    $count = null;
    foreach($theme_files as $file) {
        $file_contents = file_get_contents($file);
        $count++;
        if(strpos($file_contents, 'Main')) {
            $array_pos = $count;
            $main_file = $theme_files[$array_pos];

            echo $main_file;
        }
    }
}

因为你可以看到我将所有找到的文件添加到一个数组中,然后得到每个文件的内容,并搜索它查找变量'Main',如果找到变量,得到当前自动递增数字,并从数组中获取路径,但它总是告诉我错误的文件,它没有任何接近'Main'。

我认为像Wordpress这样的CMS使用类似的功能进行插件开发,在其中搜索所有文件以获取正确的插件详细信息(这是我想要制作的,但是对于主题)。

谢谢, 基隆

1 个答案:

答案 0 :(得分:1)

就像大卫在他的评论中所说,数组在php中是零索引。 $ count在被用作$ theme_files的索引之前递增($ count ++)。将$ count ++移动到循环的末尾,并在索引查找后递增。

public function build_active_theme() {
$dir = CONTENT_DIR . 'themes/' . $this->get_active_theme() . '/';

$theme_files = array();
foreach(glob($dir . '*.php') as $file) {
    $theme_files[] = $file;
}

$count = null;
foreach($theme_files as $file) {
    $file_contents = file_get_contents($file);
    if(strpos($file_contents, 'Main')) {
        $array_pos = $count;
        $main_file = $theme_files[$array_pos];

        echo $main_file;
    }
    $count++;
}

}

相关问题