2012-03-15 68 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']; 
    } 
}