好吧,我正在逐行阅读文件。我知道文件中的每个函数名称,因为它是在XML文档中的其他地方定义的。那应该是这样的:如何从文件中获取整个函数
function function_name
其中function_name是函数的名称。
我从一个XML文档中获得了所有的函数定义,我已经将这些函数定义放入一个函数名称数组中,并且我需要从php文件中抓取这些函数。并重新构建该PHP文件,以便它只包含这些功能。也就是说,如果一个php文件的功能比XML标签中定义的要多,那么我需要去除这些功能,并且只用用户在XML文件中指定的函数重写.php文件。
所以,我面临的困境是如何确定逐行读取函数的END,并且我意识到函数可以包含函数。所以我不想删除它们中的功能。只是独立的函数,没有在随附的XML文件中定义。任何想法如何做到这一点?
好吧,我现在使用下面的功能:
//!!! - Used to grab the contents of all functions within a file with the functions array.
function get_functions($source, $functions = array())
{
global $txt;
if (!file_exists($source) || !is_readable($source))
return '';
$tokens = token_get_all(file_get_contents($source));
foreach($functions as $funcName)
{
for($i=0,$z=count($tokens); $i<$z; $i++)
{
if (is_array($tokens[$i]) && $tokens[$i][0] == T_FUNCTION && is_array($tokens[$i+1]) && $tokens[$i+1][0] == T_WHITESPACE && is_array($tokens[$i+2]) && $tokens[$i+2][1] == $funcName)
break;
$accumulator = array();
// collect tokens from function head through opening brace
while($tokens[$i] != '{' && ($i < $z)) {
$accumulator[] = is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i];
$i++;
}
if($i == $z) {
// handle error
fatal_error($txt['error_occurred'], false);
} else {
// note, accumulate, and position index past brace
$braceDepth = 1;
$accumulator[] = '{';
$i++;
}
while($braceDepth > 0 && ($i < $z)) {
if(is_array($tokens[$i]))
$accumulator[] = $tokens[$i][1];
else {
$accumulator[] = $tokens[i];
if($tokens[$i] == '{') $braceDepth++;
else if($tokens[i] == '}') $braceDepth--;
}
$i++;
}
$functionSrc = implode(null,$accumulator);
}
}
return $functionSrc;
}
OK,所以它需要这个PHP文件内容:
<?php
function module_testing($params)
{
// Is it installed?
$test_param = !isset($params['test_param']) ? 'Testing Testing 1 2 3!' : $params['test_param'];
// Grab the params, if they exist.
if (is_array($params))
{
echo $test_param;
}
// Throw an error.
else
module_error();
}
?>
,并改变它,像这样:
<?php
function module_testing($params)
{
// Is it installed?
$test_param isset$params'test_param' 'Testing Testing 1 2 3!' $params'test_param'
// Grab the params, if they exist.
if is_array$params
echo $test_param
// Throw an error.
else
module_error
?>
正如你所看到的,它在这里花了一大堆东西。并且最后一个右括号缺失......我需要做的就是检查函数是否存在于function module_testing
中,并获取整个函数并将其写入同一个文件。看起来很简单,但天啊,这只是IMO这个小东西的一些主要编码...
Or I could also check if a function is defined in here that isn't within the $functions array, if so, than just remove that function. Perhaps it's easier with this approach instead??
伙计们,我已经解决了这个问题。请参阅下面的答案。再次感谢:) – SoLoGHoST 2010-05-02 06:40:27