【问题标题】:Searching for a specific string from all PHP files in the parent directory从父目录中的所有 PHP 文件中搜索特定字符串
【发布时间】:2016-07-12 19:02:37
【问题描述】:

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

谢谢, 基隆

【问题讨论】:

  • 数组索引为 0,因此在运行 if 之前 $count++ 将始终从 1 开始,这意味着您将文件拉到您想要的文件旁边
  • 好的,也许 $count++ +1 会起作用?编辑:现在我收到错误“注意:未定义的偏移量:3”

标签: php wordpress function loops oop


【解决方案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++;
}

}

【讨论】:

  • 谢谢!仍然掌握自动递增/循环。标记为答案!
猜你喜欢
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2013-11-27
  • 2018-05-05
  • 2018-03-24
相关资源
最近更新 更多