2015-11-02 23 views
-1

我有一個多行字符串,並有2個字符在行。 我想在一段時間內讀取腳本行 獲取第一個字和第二個字。PHP while while從字符串讀取多行文本

$multilinestring="name1 5 
name2 8 
name3 34 
name5 55 "; 

我想有而我讀通過線串線是獲得 2個串

$firstword$secondword

謝謝大家提前結果!

回答

1

如果這是真的,你想讀的文本文件,然後你會更好的使用fgets()或讀取文件到一個數組完全file()和使用explode()之後。考慮這個代碼:

$arr = file("somefile.txt"); // read the file to an array 
for ($i=0;$i<count($arr);$i++) { // loop over it 
    $tmp = explode(" ", $arr[$i]); // splits the string, returns an array 
    $firstword = $tmp[0]; 
    $secondword = $tmp[1]; 
} 
1

使用while循環來做到這一點有什麼意義?使用foreach循環來實現這一目標:

foreach (explode("\n", $multilinestring) as $line) { 
    $line = explode(" ", $line); 
    print_r($line); 
} 
1

使用此:

$eachLine = explode(PHP_EOL, $multilinestring); // best practice is to explode using EOL (End Of Line). 
foreach ($eachLine as $line) { 
    $line = explode(" ", $line); 
    $firstword = $line[0]; 
    $secondword = $line[1]; 
}