---
title: "语法分析函数"
author: "muyu"
date: "2009-08-20T11:46:20Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-08-20T11:49:38Z"
id: 453473
url: "https://muyu.iteye.com/blog/453473"
---

如何完整地从一个文本中获取一个function函数块？

 

通过堆栈，辨别“{”、“}”出现的顺序、次数：

1. 碰到“{”，push一下；碰到“}”，pop一次。
2. 每次碰到“}”，都要判断一下堆栈是否已经为空了，如果为空，表示获取了完整的代码块。
3. 注意考虑出现在单行注释、多行注释中的“{”、“}”。

 

函数实现如下：

 

```
/**
 * 返回函数体字符串
 *
 * @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”---格式化代码---的功能。

如果考虑到语句结束符、缩进规则，可以解析源代码，然后再调用编译器了。