从父目录中的所有PHP文件中搜索特定字符串


Searching for a specific string from all PHP files in the parent directory

我正试图找到一种方法来搜索父目录中的所有*.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在插件开发中使用了类似的功能,它在所有文件中搜索正确的插件详细信息(这是我想要做的,但对于主题)。

谢谢,Kieron

正如David在评论中所说,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++;
}

}