How to extract the first word from each line of a text file in PHP

1 Answer

0 votes
function get_first_words() {
    $firstWords = array();
    $file = file("data.txt");
    foreach ($file as $line) {
        if (trim($line) != '') {
            $expl = explode(" ", $line);
            $firstWords[] = $expl[0];
        }
    }
    return $firstWords;
}

echo implode(', ', get_first_words());



/*
run:

PHP, that, It, Rasmus, PHP

*/

 



answered Jul 27, 2020 by avibootz

Related questions

1 answer 218 views
1 answer 189 views
1 answer 182 views
1 answer 218 views
1 answer 197 views
...