简体   繁体   中英

How to read a text file contents word by word in an array in php

I have a text file with 8-10 words in each line with sequence no.and spaces. eg 1)word 2)word 3)word 4)word ......... and i want to read it in an one dimensional array only words not sequence no.

Assuming your file looks like this:

1)First 2)Second 3)Third 4)Forth
5)Fifth 6)Sixth ..

Using this function you can extract the word only:

preg_match_all('/[0-9]+\)(\w+)/', $file_data, $matches);

Now $matches[1] will contain:

 Array
    (
        [0] => First
        [1] => Second
        [2] => Third
        [3] => Fourth
        [4] => Fifth
        [6] => Sixth
    )

First of all if you have each word on new line then you get lines first:

$contents = file_get_contents ($path_to_file);
$lines = explode("\n", $contents);
if (!empty($lines)) {
    foreach($lines as $line) {
        // Then you get rid of sequence
        $word_line = preg_replace("/^([0-9]\))/Ui", "", $x);
        $words = explode(" ", $word_line); 
    }
}

(assuming sequence starts with "x)" )

Assuming file contents is just like what duckyflip illustrated, another possible way

$content = file_get_contents("file");
$s = preg_split("/\d+\)|\n/",$content);
print_r(array_filter($s));

output

$ php test.php
Array
(
    [1] => First
    [2] => Second
    [3] => Third
    [4] => Forth
    [6] => Fifth
    [7] => Sixth
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM