2012-03-03 96 views
0

我想從文本文件中分割字符串。從文本文件中獲取字符串並分成數組

如果.txt文件已從某位置讀取。我想讀取文件並獲取數組中的字符串。

文本文件中有如下數據

aaa 1111111, 
    2hajakka, 
    87uj5687, 
    F2tryty 
bbb 45454545, 
    rereer, 
    87uj5687, 
    4343343, 
    944dsdds 

我想要存儲在陣列線像

$arr = array(
"aaa 1111111, 2hajakka, 87uj5687, F2tryty ", 
"bbb 45454545, rereer, 87uj5687, 4343343, 944dsdds"); 

筆記:
數據必須開始第一行的名稱,如(AAA,BBB)數據的被逗號隔開。如果沒有逗號在它進入下一個陣列場提前

由於線路

+0

你問像1-1 = 2(你的期望)!怎麼樣!!!!!它的位置。 – K6t 2012-03-03 12:00:54

回答

0
$file_handle = fopen("myfile.txt", "r"); 
$arr[] = ""; 
$i = 0; 
$temp_string = ''; 

while (!feof($file_handle)) { 
$line = fgets($file_handle); 
if(strpos($line,",")!== false) 
{ 
$temp_string = $temp_string.$line;} 
else{ 
$temp_string = $temp_string.$line; 
$arr[$i] = $temp_string; 
$temp_string = ''; 
$i++;} 
} 
+0

謝謝kaushtuv – satheesh 2012-03-03 14:32:13

+0

隨時。那是否工作? – Kaushtuv 2012-03-03 23:50:35

0

你正在試圖做的是非常簡單的:

  1. 崩潰多行記錄到一個單一的線
  2. 線分割​​成的陣列

幾乎:

<?php 
$string = 'aaa 1111111, 
    2hajakka, 
    87uj5687, 
    F2tryty 
bbb 45454545, 
    rereer, 
    87uj5687, 
    4343343, 
    944dsdds'; 

// move lines beginning with a space to the previous line 
$string = preg_replace('#\n +#', ' ', $string); 
// split lines into array 
$array = explode("\n", $string); 
var_dump($array); 
+0

感謝你羅德尼,但我有另一個疑問,如果我給數據的空間,如「1111 111,2ha ja kka,87 uj5 687,F 2try ty」我如何使用preg_replace – satheesh 2012-03-03 14:27:26

+0

這些空間的行爲究竟如何? – rodneyrehm 2012-03-03 14:59:31

+0

像這樣rodney,J1.A1 DUT.A1 DUT.A2 C1.1 C2.1,F2.1 F4.1 K1.1,F2.1 F4.1 K1.1,F2.1 F4.1 K1.1 – satheesh 2012-03-05 11:26:43

相關問題