如何完整地從一個文本中獲取一個function函數塊?
通過堆棧,辨別“{”、“}”出現的順序、次數:
- 碰到“{”,push一下;碰到“}”,pop一次。
- 每次碰到“}”,都要判斷一下堆棧是否已經爲空了,如果爲空,表示獲取了完整的代碼塊。
- 注意考慮出現在單行註釋、多行註釋中的“{”、“}”。
函數實現如下:
/**
* 返回函數體字符串
*
* @param string $blockStart
* @param string $codeStr
* @return string / false
*/
function getCodeBlock($blockStart, $codeStr) {
$str = $codeStr;
$pos = strpos($codeStr, $blockStart);
if (false === $pos) {
return false;
}
$len = strlen($str);
$stack = array();
$search = '';
$commentSingle = false;
$commentMultiline = false;
for($i=$pos; $i<$len; $i++) {
$tmp = $str[$i];
$search .= $tmp;
//處理單行註釋 //....
if (!$commentMultiline) {
if ($i>1 && "/" == $tmp && "/" == $str[$i-1]) {
$commentSingle = true;
}
if ($commentSingle && "\n" == $str[$i]) {
$commentSingle = false;
}
}
//處理多行註釋 /* .. */
if ($i>1 && "*" == $tmp && "/" == $str[$i-1]) {
$commentMultiline = true;
}
if ($commentMultiline && "/" == $tmp && "*" == $str[$i-1]) {
$commentMultiline = false;
}
//記錄"{"、"}"
if (!$commentSingle && !$commentMultiline) {
if ('{' == $tmp) {
$stack[] = '{';
}
if ('}' == $tmp) {
array_pop($stack);
if (empty($stack)) {
break;
}
}
}
}
return $search;
}
---------------
引申
---------------
有了這個函數,可以做編輯器裏常用的“format”---格式化代碼---的功能。
如果考慮到語句結束符、縮進規則,可以解析源代碼,然後再調用編譯器了。