2010-04-16 195 views
0

我想检查括号,开放和关闭象下面这样打开.txt文件:PHP大括号到数组

file { 

nextopen { 
//content 
} 

} 

不,这不是我自己的语言或什么,但我希望得到说nextopen函数和括号内的所有内容,以及所有来自文件函数内的东西,并将其添加到数组中,如果你知道我的意思。所以大括号内的所有内容都将放在一个数组中。如果你知道如何做到这一点,请回复。

阵列应该是这样的:

array(
[file] => '{ nextopen { //content } }', 
[nextopen] => '{ //content }' 
); 
+0

不,我不知道你的意思。你能举一个例子来说明结果数组应该是什么样子? – 2010-04-16 03:41:32

+0

增加了数组应该看起来像 – David 2010-04-16 03:44:10

+1

这可能不会像人们直觉上想的那样微不足道。您需要标记输入。为此,您需要提供关于输入语法的更多输入。例如;标识符的标准是什么? (换行符,空格,字符等)。请参阅维基百科有关词汇分析的文章,了解为什么它不那么简单:http://en.wikipedia.org/wiki/Lexical_analysis – 2010-04-16 03:55:17

回答

3

这种情况的基本算法中像下面

  1. 每一个序列{ no-braces-here },把它放在一个缓冲区中,与一个神奇的数字标识更换其在缓冲区中的位置
  2. 重复(1)直到找不到更多的序列
  3. 对于缓冲区中的每个条目 - 如果它包含魔术数字,用缓冲区中的相应字符串替换每个数字。
  4. 缓冲区就是我们在PHP中寻找

class Parser 
{ 
    var $buf = array(); 

    function put_to_buf($x) { 
     $this->buf[] = $x[0]; 
     return '@' . (count($this->buf) - 1) . '@'; 
    } 

    function get_from_buf($x) { 
     return $this->buf[intval($x[1])]; 
    } 

    function replace_all($re, $str, $callback) { 
     while(preg_match($re, $str)) 
      $str = preg_replace_callback($re, array($this, $callback), $str); 
     return $str; 
    } 

    function run($text) { 
     $this->replace_all('~{[^{}]*}~', $text, 'put_to_buf'); 
     foreach($this->buf as &$s) 
      $s = $this->replace_all('[email protected](\d+)@~', $s, 'get_from_buf'); 
     return $this->buf; 
    } 



} 

测试

$p = new Parser; 
$a = $p->run("just text { foo and { bar and { baz } and { quux } } hello! } ??"); 
print_r($a); 

结果

Array 
(
    [0] => { baz } 
    [1] => { quux } 
    [2] => { bar and { baz } and { quux } } 
    [3] => { foo and { bar and { baz } and { quux } } hello! } 
) 

让我知道如果您有任何问题1附件。