从一组特定的 PHP 源文件中获取包含文件的列表


Get list of include files from a specifc set of PHP source files

>我需要 PHP 中的脚本来读取其他 PHP 源文件并提取包含、require 和 require once 函数中引用的文件路径。我特别需要它来创建部署项目,以便输出包可能只包含项目中使用的库文件夹中的文件。

PHP 中是否有任何函数可以读取源文件并提取 require、include 和 require_once 语句中的路径?

这是正确的答案,它实际上解析了PHP语法。请注意,不可能真正做你想做的事。例如,您可能有自动加载程序或无法自动提取的变量包含路径。

<?php
$required_file    = '';
$required_files   = array();
$is_required_file = false;
// Parse the PHP source using the Tokenizer library (PHP 4.3.0+)
$tokens           = token_get_all($text);
foreach ($tokens as $token) {
    // Get the token name to make our code more readable.
    $token_name = is_int($token[0]) ? token_name($token[0]) : $token[0];
    echo $token[0]. ': ' . htmlentities($token[1]) . '<br>';
    // Is this token a require/include keyword?
    if (in_array($token_name, array('T_INCLUDE', 'T_INCLUDE_ONCE', 'T_REQUIRE', 'T_REQUIRE_ONCE'))) {
        $is_required_file = true;
    }
    elseif ($is_required_file && $token[0] != ';' && $token[0] != '.' && $token_name != 'T_WHITESPACE') {
        if ($token_name == 'T_STRING') {
            $token[1] = '{{CONST:' . $token[1] . '}}';
        }
        $required_file .= $token[1] ? trim($token[1], '''"') : $token[0];
    }
    elseif ($is_required_file && $token[0] == ';') {
        $is_required_file = false;
        $required_files[] = trim($required_file, ' ()');
        $required_file    = '';
    }
}

$required_files是文件的数组。匹配requirerequire_onceincludeinclude_once

对于以下输入:

<?php
include APPLICATION_MODULES_ROOT . 'test1.php';
include($some_var . 'test55.php');
include('test2.php');
include ('test3.php');
include_once 'test4.php';
include_once('test5.php');
include_once ('test6.php');
require 'test7.php';
require('test8.php');
require ('test9.php');
//require ('test99.php');
require_once 'test10.php';
require_once('test11.php');
require_once ('test12.php');

你最终得到这个:

Array
(
    [0] => {{CONST:APPLICATION_MODULES_ROOT}}test1.php
    [1] => test55.php
    [2] => test2.php
    [3] => test3.php
    [4] => test4.php
    [5] => test5.php
    [6] => test6.php
    [7] => test7.php
    [8] => test8.php
    [9] => test9.php
    [10] => test10.php
    [11] => test11.php
    [12] => test12.php
)

您所要做的就是使用 str_replace 或类似替换应用程序使用的常量。

重要说明:这不适用于变量包含名称,例如 include $some_path; .您无法解析这些内容。

尝试这样的事情:

<?php 
$source = file_get_contents('source.php');
preg_match_all('/(include|include_once|require|require_once) *'(? *[''"](.*?)[''"] *')? *;/', $source, $matches);
$files = $matches[2];

$files现在是包含/必需的文件数组。

不过,这不是一个合适的解决方案,因为它会匹配注释掉的代码。