2012-10-23 25 views
0

任何人都可以在以下內容中提供幫助。我在mysql表中有一個「註釋」字段,但需要將它分離到一個新表中。使用php從大文本中獲取多個信息到數組中

該說明是在目前這種格式:

添加人USERNAME1上22/10/2012下午3:50

該說明是在這裏

添加人USERNAME2 20/10/2012下午12時29

該說明是在這裏等

這裏有2個筆記作爲例子。我怎樣才能得到這到一個數組這樣的:

[0] => Array(
     [0] username1 
     [1] 22/10/2012 3:50pm 
     [2] Note1 
    ) 
[1] => Array(
     [0] username2 
     [1] 20/10/2012 12:29pm 
     [2] Note2 
    ) 

我試着使用使preg_split但僅當「通過日期 - 時間的用戶名添加」分裂退貨注意,因爲我不能用「添加有」其自己分裂它作爲說明本身可能包含「添加」

什麼是最好的方式來做到這一點?

感謝

+0

那麼它是一個文本區域還是每個音符都被分隔到自己的行中? – Pitchinnate

+0

筆記是數據庫中單個字段中的單個文本。例如上面的例子將是單行中的一個字段。 – Onimusha

回答

2

試試這個

// Get the data from the database 
$myData = $row['notes']; 

// Split this into an array 
$data = explode("\r\n", $myData); 

// $data has each line as an element of the array 
$key = -1; 
$final = array(); 
foreach ($data as $element) 
{ 
    // Check if this is the first row 
    if (strpos($element, "Added by") > 0) 
    { 
     $key = $key + 1; 
     // This is the first header row. Get the info from it 
     $tmp = str_replace("Added by", "", $element); 
     $parts = explode(" on ", $tmp) 

     // Add them to the final array 
     // Username 
     $final[$key][0] = trim($parts[0]); 
     // Date 
     $final[$key][1] = trim($parts[1]); 

     // Initialize the note element 
     $final[$key][2] = ''; 
    } 
    else 
    { 
     // We don't have the 'Added On' so add this as a note. 
     $final[$key][2] .= $element; 
    } 
} 

這應該給你的基礎上下工夫。您還可以檢查筆記元素中的空行$final[$key][2] .= $element;

+0

好吧,這很好地工作。做得好。必須糾正'$ final [$ key] [0] = trim($ tmp [0]);''到'$ final [$ key] [0] = trim($ parts [0]);' – Onimusha

+0

確認對不起。現在在回覆中進行更正。 –

0

可能是你最好的選擇是該領域啜入線的陣列,則每行迭代。如果你點擊一條看起來像Added的線,就會得到一條新的記錄,然後每條後續的線都是註釋的一部分......直到你點擊另一條添加線。

例如

$lines = array(... your monolithic text here ...); 
$idx = 0; 
$notes = array(); 
foreach($lines as $line) { 
    if (preg_match('/^Added by (.*?) on (.*?)$/', $matches)) { 
     $notes[$idx] = array(
      0 => $matches[1], // username 
      1 => $matches[2], // date/time 
      2 => '' // note text 
     ) 
     continue; 
    } 
    $notes[$idx[2]] .= $line; 
} 
+0

你不需要增加'$ idx'嗎?也不應該是'$ notes [$ idx] [2]。= $ line;' – Pitchinnate

+0

這一個沒有工作。謝謝雖然:)接受的答案使用相同的技術,但作品 – Onimusha