2012-03-15 73 views
0

我爲一個電視節目創建了一個「引用數據庫」,我很喜歡,我正在重寫它的一部分,我並不特別喜歡。我遇到了我的函數來解析包含引號和字符的數據到一個數組中,我可以輕鬆地循環和顯示。該網站的其中一項功能是您可以使用單引號(單行)或幾個字符之間的對話。現在我正在存儲像這樣的單引號:解析數據到數組

[charactername]這是我的詼諧單線。

和對話遵循相同的模式:

[characternameone]天氣如何?

[characternametwo]其實很好。

依此類推。這是前面提到的解析函數:

function parse_quote($text) 
{ 
    // Determine if it's a single or convo 
    if (strpos($text, "\n") != false) 
    { 
     // Convo 
     // Let's explode into the separate characters/lines 
     $text = explode("\n", $text); 
     $convo = array(); 

     // Parse each line into character and line 
     foreach ($text as $part) 
     { 
      $character = substr($part, 1, strpos($part, ']') - 1); 
      $line = substr($part, strlen($character) + 2); 
      $convo[] = array(
       'character' => $character, 
       'line' => $line 
      ); 
     } 

     return array(
      'type' => 'convo', 
      'quote' => $convo 
     ); 
    } 
    else 
    { 
     // Single 
     // Parse line into character and line 
     return array(
      'type' => 'single', 
      'quote' => array(
       'character' => substr($text, 1, strpos($text, ']') - 1), 
       'line' => substr($text, strlen(substr($text, 1, strpos($text, ']') - 1)) + 2) 
      ) 
     ); 
    } 
} 

它按預期工作,但我不禁想到有更好的方法來做到這一點。我對正則表達式感到可怕,我認爲這種情況至少在某種程度上會有所幫助。任何建議或改進?

+1

是的,使用數據庫:) SQLite可能 – 2012-03-15 18:52:37

+0

'$ text'來自數據庫;這就是它的存儲方式。我將如何改進?也許我應該在存儲之前序列化這個東西? – 2012-03-15 18:54:04

+1

那麼,你沒有提到,所以我猜「平面文件」的意思就是這樣。一種提升?在字符名稱中使用一列(在與報價相關的表格中),因此您不必解析任何內容,只需在正確索引的列上使用選擇即可。方式更簡單,性能更高 – 2012-03-15 18:55:32

回答

0

而不是

 $character = substr($part, 1, strpos($part, ']') - 1); 
     $line = substr($part, strlen($character) + 2); 
     $convo[] = array(
      'character' => $character, 
      'line' => $line 
     ); 

你可以嘗試

 preg_match('#\[([^\]]+)\](.*)#ism', $part, $match); 
     $convo[] = array(
      'character' => $match[1], 
      'line' => $match[2] 
     ); 

HTH

1

就個人而言,我會改變你的數據存儲方法。處理序列化或JSON編碼的字符串會容易得多。

而不是

[characternameone]How's the weather? 
[characternametwo]Pretty good, actually. 

你會

array(
    [0] => { 
    'name' => "characternameone", 
    'quote' => "How's the weather?" 
    }, 
    [1] => { 
    'name' => "characternametwo", 
    'quote' => "Pretty good, actually" 
    } 
) 

然後,當你讀出來,沒有任何分析。

function display_quote($input) 
{ 
    for ($i=0, $n=count($input); $i<$n; $i++) { 
    $quote = $input[$i]; 
    if ($i > 0) echo "\n"; 
    echo $quote['name'] . ': ' . $quote['quote']; 
    } 
}