如何从文件中获取整个函数 [英] How to get the Entire Function from a file

查看:125
本文介绍了如何从文件中获取整个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在逐行阅读一个文件。我知道文件中的每个函数名称,因为它是在XML文档中的其他地方定义的。那应该是这样的:

pre $函数函数名
code $ pre >

其中function_name是函数的名称。



我已经从一个XML文档中获得了所有的函数定义已经放入了一个函数名称数组,我需要从php文件中抓取这些函数。并重新构建该php文件,使其只具有这些功能。也就是说,如果一个php文件的功能比XML标签中定义的要多,那么我需要去掉这些功能,并且只用用户在XML文件中指定的函数来重写.php文件。 / p>

所以,我面对的困境是如何确定逐行读取函数的END,而且我知道函数可以在其中有函数。所以我不想删除它们中的功能。只是功能是独立的,没有在随附的XML文件中定义。任何想法如何做到这一点?

好吧,我现在使用以下函数:

  //! - 用于使用函数数组获取文件内所有函数的内容。 
函数get_functions($ source,$ functions = array())
{
global $ txt;

if(!file_exists($ source)||!is_readable($ source))
return'';

$ tokens = token_get_all(file_get_contents($ source)); ($ i = 0,$ z = count($ tokens); $ i <$ z; $ i ++)
$ b foreach($函数为$ funcName)
{

if(is_array($ tokens [$ i])&& $ $ tokens [$ i] [0] == T_FUNCTION&&&& )&& $ $ tokens [$ i + 1] [0] == T_WHITESPACE&&& is_array($ tokens [$ i + 2])&& $ tokens [$ i + 2] [1] = = $ funcName)
break;

$ accumulator = array();
//从函数头通过开始的大括号收集令牌
while($ tokens [$ i]!='{'&&($ i< $ z)){
$ accumulator [] = is_array($ tokens [$ i])? $ tokens [$ i] [1]:$ tokens [$ i];
$ i ++;

if($ i == $ z){
//处理错误
fatal_error($ txt ['error_occurred'],false);
} else {
//注意,累加和位置索引过去大括号
$ 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;

$ / code>

好的,所以需要这个php文件内容:

 <?php 
function module_testing($ params)
{
//是否已安装?
$ test_param =!isset($ params ['test_param'])? '测试测试1 2 3!':$ params ['test_param'];

//抓住参数,如果存在的话。
if(is_array($ params))
{
echo $ test_param;
}
//抛出一个错误。
else
module_error();
}

?>

并改变它:

<?php 

函数module_testing($ params)

{

//是否已安装?

$ test_param isset $ params'test_param''测试测试1 2 3!'$ params'test_param'



//抓取参数,如果它们存在的话。

if isarray $ params


$ b echo $ test_param



// Throw一个错误。

else

module_error





?>

正如您所看到的,这里花了一大堆东西。最后一个右括号缺失...我需要做的就是检查函数是否存在于 function module_testing 中,并抓取整个函数并写入相同文件。似乎很简单,但魔兽世界,这是一些主要编码只是这个小事情国际海事组织... ... $ / b
$ b


或者我也可以检查是否函数是在这里定义的
,它不在
$函数数组中,如果是这样的话,那么
就不能移除那个函数。也许这是
更方便的方法,而不是??


解决方案

我设法解决这个完美的罚款,并在我自己的,这里是完美的解决方案。我想感谢大家的帮助。谢谢,你们已经远远超出了帮助我。但我知道这将是一个简单的解决方案,而不使用标记器函数。也许你们忘记了我有每个功能的名字?在任何情况下,再次感谢,但令牌功能将不需要为此。



干杯。



<$ ($ source $ array $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
返回'';

$ code ='';
$ removeStart = false;

$ fp = fopen($ source,'rb');
while(!feof($ fp))
{
$ output = fgets($ fp);
$ funcStart = strpos(strtolower($ output),'function');
$ b $ if($ funcStart!== false)
{
foreach($函数为$ funcName)
{
if(strpos($ output, $ funcName)!== false)
{
$ code。= $ output;
$ removeStart = false;
break;
}
else
$ removeStart = true;
}
继续;



if(substr($ output,0,2)=='?>'||!$ removeStart)
$ code。 = $输出;
}
}
fclose($ fp);

//用定义的函数重写文件。
$ fo = @fopen($ source,'wb');

//删除多余的行...
@fwrite($ fo,str_replace(\r\\\
,\\\
,$ code)) ;

fclose($ fo);





$ p

这会使得如果函数内部有一个函数,比用户需要定义它,否则,功能将无法正常工作。所以这对我来说并不是什么大不了的事情,因为它们可以有无限的功能,并且更好地适应每个函数本身的功能。


Ok, I'm reading through a file now, line by line. I know each functions name in the file, since it is defined elsewhere in an XML document. That is what should be this:

function function_name

Where function_name is the name of the function.

I get all of the function definitions from an XML document that I already have put into an array of function names, and I need to grab just those functions from the php file. And rebuild that php file so that it only has those functions in it. That is to say, if a php file has more functions than what is defined in the XML tag, than I need to strip out those functions, and rewrite the .php file with only the functions that the user specified in the XML file.

So, the dilemma I face is how to determine the END of a function reading line by line, and I'm aware that functions can have functions within them. So I don't want to remove the functions within them. Just functions that are standalone and aren't defined within the accompanying XML file. Any ideas on how to do this??

Ok, I'm using the following function now:

//!!! - 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, so it takes this php files content:

<?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();
}

?>

and changes it like so:

<?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





?>

As you can see it took a whole bunch of stuff outta here. And the last closing bracket is missing... All I need to do is check if the function exists in here function module_testing, and grab the entire function and write it to the same file. Seems simple enough, but WoW, this is some major coding for just this minor thing 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??

解决方案

Ok, guys, I managed to fix this perfectly fine, and on my own, and here is the perfect solution. I want to thank you all for your help with this. Thanks, you guys have gone far beyond helping me here. But I knew this would be a simple solution without using the tokenizer functions. Perhaps you guys have forgotten that I have the name of each function? In any case, thanks again, but the token functions won't be needed for this.

Cheers.

function remove_undefined_functions($source, $functions = array())
{
    if (!file_exists($source) || !is_readable($source))
        return '';

    $code = '';
    $removeStart = false;

    $fp = fopen($source, 'rb');
    while (!feof($fp))
    {
        $output = fgets($fp);
        $funcStart = strpos(strtolower($output), 'function');

        if ($funcStart !== false)
        {
            foreach($functions as $funcName)
            {
                if (strpos($output, $funcName) !== false)
                {
                    $code .= $output;
                    $removeStart = false;
                    break;
                }
                else
                    $removeStart = true;
            }
            continue;
        }
        else
        {
            if (substr($output, 0, 2) == '?>' || !$removeStart)
                $code .= $output;
        }
    }
    fclose($fp);

    // Rewrite the file with the functions that are defined.
    $fo = @fopen($source, 'wb');

    // Get rid of the extra lines...
    @fwrite($fo, str_replace("\r\n", "\n", $code));

    fclose($fo);
}

And this will make it so that if there is a function inside of a function, than the user will have to define it, otherwise, the function will not work properly. So this isn't really a big deal to me, since they can have an unlimited amount of functions, and would better suited that each function is a function to itself.

这篇关于如何从文件中获取整个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆