2015-11-02 35 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]; 
}