2010-05-17 66 views
1

我們無法拆分下面的code.please字符串幫助我們。explode不工作,拆分字符串

<?php 
$i=0; 
$myFile = "testFile.txt"; 
$fh = fopen($myFile, 'a') or die("can't open file"); 
$stringData = "no\t"; 
fwrite($fh, $stringData); 
$stringData = "username \t"; 
fwrite($fh, $stringData); 
$stringData ="password \t"; 
fwrite ($fh,$stringData); 

$newline ="\r\n"; 
fwrite ($fh,$newline); 
$stringData1 = "1\t"; 
fwrite($fh, $stringData1); 
$stringData1 = "srinivas \t"; 
fwrite($fh, $stringData1); 
$stringData1 ="malayappa \t"; 
fwrite ($fh,$stringData1); 


fclose($fh); 



?> 
$fh = fopen("testFile.txt", "r"); 
$ 
while (!feof($fh)) { 
$line = fgets($fh); 
echo $line; 
} 

fclose($fh); 
$Beatles = array('pmm','malayappa','sreenivas','PHP'); 

for($i=0;$i<count($Beatles);$i++) 
{ 
if($i==2) 
{ 

echo $Beatles[$i-1]; 
echo $Beatles[$i-2]; 

} 
} 
$pass_ar=array(); 
$fh = fopen("testFile.txt", "r"); 
while (!feof($fh)) { 
$line = fgets($fh); 
echo $line; 
$t1=explode(" ",$line); 

print_r($t1); 
array_push($pass_ar,t1); 
} 

fclose($fh); 
+0

固定您的格式(至少有一點)。請用樣本字符串和爆炸創建一個測試用例,這可能有助於我們幫助您。 – dbemerlin 2010-05-17 13:55:55

+0

請指定什麼不工作,以及數據看起來像你想分裂。 – 2010-05-17 13:56:00

+0

用print_r($ t1)得到的輸出是什麼;'? – Sarfraz 2010-05-17 13:56:05

回答

0

你正在爆炸空白。除非弦內有空白,否則爆炸,否則不起作用。

嘗試使用代碼標記使您的代碼更具可讀性,以獲得更好的人員質量響應。

1

如果我讀碼正確,你正在編寫由\ t分隔的字符串,但試圖用空間爆炸,使用:

explode("\t", $string); 
1

你可以使用fgetcsv,因爲你只是在做一個標準的製表分隔的輸入文件。鑑於您的樣本文件:

no [tab] username [tab] password 
1 [tab] srinivas [tab] malayappa 

然後

$lines = array(); 
$fh = fopen('testfile.txt', 'rb') or die ("can't open testfile.txt"); 
while($lines[] = fgetcsv($fh, 0, "\t") { // no line length limit, tab delimiter) 
    ... 
} 

會給你

$lines = Array(
    0 => Array(
     0 => 'no ', 
     1 => 'username ', 
     2 => 'password ' 
    ), 
    1 => Array(
     0 => 1, 
     1 => 'srinivas ', 
     2 => 'malayappa' 
    ) 
);