抓住每一行的第一个字

时间:2013-06-04 19:47:39

标签: php file-get-contents

我有一个文本文件,我想要抓住每个第一个单词:

  

名字|全部| 01.01.55.41

     

第二个名字|| 01.01.55.41

     

第三名|| 01.01.55.41

我正在尝试:

function get_content() {
    $mailGeteld = NULL;
        $mailGeteld = file_get_contents("content.txt");
        $mailGeteld = explode("|",$mailGeteld);
        return $mailGeteld[0];
}

但是现在我只得到“名字”,我该如何循环呢,结果如下:

  

名字,第二名,第三名

3 个答案:

答案 0 :(得分:4)

file逐行读取文件。

function get_content() {
        $firstWords = array();
        $file = file("content.txt"); //read file line by line
        foreach ($file as $val) {
            if (trim($val) != '') { //ignore empty lines
                $expl = explode("|", $val);
                $firstWords[] = $expl[0]; //add first word to the stack/array
            }
        }
        return $firstWords; //return the stack of words - thx furas ;D
}

echo implode(', ', get_content()); //puts a comma and a blankspace between each collected word

答案 1 :(得分:1)

您可以使用SplFileObject

$file = new SplFileObject("log.txt", "r");
$data = array();
while(! $file->eof()) {
    $data[] = array_shift(($file->fgetcsv("|")));
}
echo implode(", ", $data);

答案 2 :(得分:0)

您的功能在一行上运行。我建议你将file_get_contents("content.txt");移出函数并迭代每一行并每次都使用你的函数。

相关问题