Searching for a specific string from all PHP files

2019-09-19 05:03发布

I am trying to figure out a way of searching through all of the *.php files inside the parent directory, parent directory example:

/content/themes/default/

I am not wanting to search through all of the files in the sub-directories. I am wanting to search for a string embedded in the PHP comment syntax, such as:

/* Name: default */

If the variable is found, then get the file name and/or path. I have tried googling this, and thinking of custom ways to do it, this is what I have attempted so far:

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;
        }
    }
}

So as you can see I added all the found files into an array, then got the content of each file, and search through it looking for the variable 'Main', if the variable was found, get the current auto-incremented number, and get the path from the array, however it was always telling me the wrong file, which had nothing close to 'Main'.

I believe CMS's such as Wordpress use a similar feature for plugin development, where it searches through all the files for the correct plugin details (which is what I want to make, but for themes).

Thanks, Kieron

1条回答
祖国的老花朵
2楼-- · 2019-09-19 05:40

Like David said in his comment arrays are zero indexed in php. $count is being incremented ($count++) before being used as the index for $theme_files. Move $count++ to the end of the loop, And it will be incremented after the index look up.

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++;
}

}

查看更多
登录 后发表回答