2011-01-20 51 views
0

嗯,我需要解析2個文本文件。 1名爲Item.txt,一個名爲Message.txt它們是遊戲服務器的配置文件,Item包含遊戲中每個項目的一行,Message包含項目名稱,描述,服務器消息等。我知道這遠遠小於理想的,但我無法改變這種工作方式或格式。用PHP解析s表達式

的想法是在Item.txt我行以這種格式

(item (name 597) (Index 397) (Image "item030") (desc 162) (class general etc) (code 4 9 0 0) (country 0 1 2) (plural 1) (buy 0) (sell 4) )

如果我有PHP變量$item等於397(指數),我需要先拿到的名字'(597)。

然後我需要打開Message.txt找到這一行

(itemname 597 "Blue Box")

然後回到「藍箱」,以PHP作爲變量。

我想要做的是返回項目的名稱與項目的索引。

我知道這可能是一個非常基本的東西,但我已經搜索了幾十個文件操作教程,但仍然無法找到我需要的東西。

感謝

+0

我不明白這一點。請提供更多關於文本文件結構的信息和期望的輸出。 – Gordon 2011-01-20 20:40:38

+1

你有沒有考慮過使用數據庫呢?大多數支持外鍵,這是爲了這種情況而設計的。否則,CSV文件的處理將比您的格式簡單得多,因爲您可以隨意使用爆炸和fgetcsv。 – GordonM 2011-01-20 20:45:17

+0

@戈登騙子!!! :D – Gordon 2011-01-20 20:47:28

回答

2

以下方法實際上並沒有 '解析' 的文件,但它應該爲您的具體問題工作...

(注:未測試)

考慮:

$item = 397; 

開放Item.txt:

$lines = file('Item.txt'); 

搜索索引$item並得到$name

$name = ''; 
foreach($lines as $line){ // iterate lines 
    if(strpos($line, '(Index '.$item.')')!==false){ 
     // Index found 
     if(preg_match('#\(name ([^\)]+)\)#i', $line, $match)){ 
      // name found 
      $name = $match[1]; 
     } 
     break; 
    } 
} 
if(empty($name)) die('item not found'); 

開放Message.txt:

$lines = file('Message.txt'); 

搜索$name並獲得$msg

$msg = ''; 
foreach($lines as $line){ // iterate lines 
    if(strpos($line, 'itemname '.$name.' "')!==false){ 
     // name found 
     if(preg_match('#"([^"]+)"#', $line, $match)){ 
      // msg found 
      $msg = $match[1]; 
     } 
     break; 
    } 
} 

$msg現在應該包含Blue Box

echo $msg; 
1

不知道如果你的問題是與解析表達式或讀取文件本身,因爲你提到的「文件操作教程」。

文件中的那些括號表達式稱爲s表達式。你可能想要谷歌的一個s表達式解析器,並將其調整爲php。

1

您應該看看serialize函數,該函數允許將數據存儲到文本文件中,格式爲PHP在需要重新加載時可以輕鬆重新解釋的格式。

將此數據序列化爲數組並將其保存到文本文件將允許您通過數組鍵訪問它。我們來舉個例子吧。作爲一個數組,您所描述的數據會是這個樣子:

$items[397]['name'] = 'bluebox'; 

序列化項目陣列將其放在可能被保存,以後訪問的格式。

$data = serialize($items); 
//then save data down to the text files using fopen or your favorite class 

然後,您可以加載文件並反序列化它的內容以最終得到相同的數組。序列化和反序列化功能直接用於此應用程序。

0

第一個文本文件有幾個功能可以用來幫助解析它。由您來決定它是否形成良好並且足夠可靠。

我注意到:

1) a record is delimited by a single line break 
2) the record is further delimted by a set of parens() 
3) the record is typed using a word (e.g. item) 
4) each field is delimited by parens 
5) each field is named and the name is the first 'word' 
6) anything after the first word is data, delimited by spaces 
7) data with double quotes are string literals, everything else is a number 

的方法:

read to the end of line char and store that 
strip the opening and closing parens 
strip all closing) 
split at (and store in temp array (see: http://www.php.net/manual/en/function.explode.php) 
element 0 is the type (e.g. item) 
for elements 1-n, split at space and store in temp array. 
element 0 in this new array will be the key name, the rest is data 
once you have all the data compartmentalized, you can then store it in an associative array or database. The exact structure of the array is difficult for me to envision without actually getting into it.