-2

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

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

4

2 回答 2

1

这是正确的答案,它实际上解析 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是文件的数组。匹配require,和. require_once_includeinclude_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;. 你无法解析这些。

于 2013-09-05T17:47:30.393 回答
1

尝试这样的事情:

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

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

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

于 2013-09-05T17:37:41.313 回答