0

PHPファイルを調べ、関数のすべてのインスタンスを見つけ、関数名を別の名前に置き換え、パラメーターを操作するスクリプトを(PHPで)書いています。get_file_contents()thenを使用しstrpos()て関数の位置を見つけていますが、関数の開始位置がわかったら、パラメーターを抽出する良い方法を見つけようとしています。現在、ファイル文字列の次の文字をウォークスルーし、開き括弧と閉じ括弧の数をカウントするループを使用しています。関数パラメーターを閉じると、終了してパラメーターの文字列を返します。残念ながら、括弧を囲む引用符 (つまりfunction_name(')', 3)) で問題が発生します。引用符を数えることもできますが、エスケープされた引用符やさまざまな種類の引用符などを処理する必要があります.

関数の開始を知って、パラメーターの文字列を確実に取得する良い方法はありますか? どうもありがとう!

4

2 に答える 2

0

次のような実際のパーサーを使用します。

https://github.com/nikic/PHP-Parser

このライブラリを使用すると、ソース コードを文字列ではなく「ノード」オブジェクトのツリーとして操作し、書き戻すことができます。

于 2013-03-31T23:31:43.717 に答える
0

EDIT: In case i didn't read the question carefully, if you want to only get function parameters,you can see these example :

$content_file = 'function func_name($param_1=\'\',$param_2=\'\'){';
preg_match('/function func_name\((.*)\{/',$content_file,$match_case);
print_r($match_case);

but if you want to manipulate the function, read below.


How about these :

  1. read file using file_get_contents();
  2. use preg_match_all(); to get all function inside that file.
  3. please not that i write /*[new_function]*/ inside that file to identify EOF.

I use this to dynamically add/ delete function without have to open that php files.

Practically, it should be like this :

//I use codeigniter read_file(); function to read the file.
//$content_file = read_file('path_to/some_php_file.php');
//i dont know whether these line below will work.
$content_file = file_get_content('path_to/some_php_file.php');
//get all function inside php file.
preg_match_all('/function (.*)\(/',$content_file,$match_case);
//
//function name u want to get
$search_f_name = 'some_function_name';
//
for($i=0;$i<count($match_case[1]);$i++){ 
    if(trim($match_case[1][$i]) == $search_f_name){ 
        break;
    } 
}
//get end position by using next function start position
if($i!=count($match_case[1])-1){
    $next_function= $match_case[1][$i+1];
    $get_end_pos = strripos($content_file,'function '.$next_function);
} else {
    //Please not that i write /*[new_function]*/ at the end of my php file 
    //before php closing tag ( ?> ) to identify EOF. 
    $get_end_pos = strripos($content_file,'/*[new_function]*/');
}
//get start position
$get_pos = strripos($content_file,'function '.$search_f_name);
//get function string
$func_string = substr($content_file,$get_pos,$get_end_pos-$get_pos);

you can do echo $func_string; to know whether these code is running well or not.

于 2013-03-31T23:02:43.047 に答える