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



Question:

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


Solution:1

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      )  


Solution:2

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)" )


Solution:3

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  )  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »