2010-04-16 128 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附件。