在考慮了This Question並給出了答案之後,我想做更多的事情來訓練自己。如何清理並簡化此代碼?
所以我寫了一個函數來計算給定函數的長度。給定的php文件必須從需要的函數開始。 舉例:如果函數是在一個大phpfile有很多的功能,如
/* lots of functions */
function f_interesting($arg) {
/* function */
}
/* lots of other functions */
然後$ 3部分的我的功能將需要開始像(有趣的功能的起始 - {
後):
/* function */
}
/* lots of other functions */
現在,這不是問題,但我想知道是否有一個更乾淨或更簡單的方法來做到這一點。這裏是我的功能:(我已經清理了很多測試 - echo
- 命令的) (其背後的思想是解釋here)
function f_analysis ($part3) {
if(isset($part3)) {
$char_array = str_split($part3); //get array of chars
$end_key = false; //length of function
$depth = 0; //How much of unclosed '{'
$in_sstr = false; //is next char inside in ''-String?
$in_dstr = false; //is nect char inside an ""-String?
$in_sl_comment = false; //inside an //-comment?
$in_ml_comment = false; //inside an /* */-comment?
$may_comment = false; //was the last char an '/' which can start a comment?
$may_ml_comment_end = false; //was the last char an '*' which may end a /**/-comment?
foreach($char_array as $key=>$char) {
if($in_sstr) {
if ($char == "'") {
$in_sstr = false;
}
}
else if($in_dstr) {
if($char == '"') {
$in_dstr = false;
}
}
else if($in_sl_comment) {
if($char == "\n") {
$in_sl_comment = false;
}
}
else if($in_ml_comment) {
if($may_ml_comment_end) {
$may_ml_comment_end = false;
if($char == '/') {
$in_ml_comment = false;
}
}
if($char == '*') {
$may_ml_comment_end = true;
}
}
else if ($may_comment) {
if($char == '/') {
$in_sl_comment = true;
}
else if($char == '*') {
$in_ml_comment = true;
}
$may_comment = false;
}
else {
switch ($char) {
case '{':
$depth++;
break;
case '}':
$depth--;
break;
case '/':
$may_comment = true;
break;
case '"':
$in_dstr = true;
break;
case "'":
$in_sstr = true;
break;
}
}
if($depth < 0) {
$last_key = $key;
break;
}
}
} else echo '<br>$part3 of f_analysis not set!';
return ($last_key===false) ? false : $last_key+1; //will be false or the length of the function
}
你想自己解析PHP嗎?這將比你想象的更復雜。 – 2010-05-03 22:25:46
不,我只想計算那些不在字符串或註釋中的'{'和'}' – user329974 2010-05-03 22:30:19