PHP: Reading word by word?

I am trying to read a file one word at a time. So far, I could use fgets () to read line by line or to a certain number of bytes, but that is not what I am looking for. I need one word at a time. until the next space, \ n or EOF.

Does anyone know how to do this in php. In C ++, I just use the cin -> var command.

+4
source share
4 answers

you can do it with

$filecontents = file_get_contents('words.txt'); $words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY); print_r($words); 

this will give you an array of words

+4
source

For some answers in this section: I say this: Do not reinvent the wheel.

In PHP use:

 str_word_count ( string $string [, int $format [, string $charlist ]] ) 

format

0 = Returns only the number of words;

1 = Returns an array;

2 = Returns an associative array;

charlist:

Charlist are the characters that you think are words.

Function.str-word-count.php

[ATTENTION]

No one knows anything about the size of your file contents, if your file contents are large, there are many flexible solutions.

(^ ‿◕)

+3
source

You will need to use fgetc to receive the letter at a time, until you click on the word bountry, and then do something with the word. Example

  $fp = fopen("file.txt", "r"); $wordBoundries = array("\n"," "); $wordBuffer = ""; while ($c = fgetc($fp)){ if (in_array($c, $wordBountries)){ // do something then clear the buffer doSomethingWithBuffer($wordBuffer); $wordBuffer = ""; } else { // add the letter to the buffer $wordBuffer.= $c; } } fclose($fp); 
+1
source

You can try the fget() function that reads a file line by line, and when you get one line from a file, you use explode() to extract a word from a line separated by a space.

Try this code:

 $handle = fopen("inputfile.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { // process the line read. $word_arr = explode(" ", $line); //return word array foreach($word_arr as $word){ echo $word; // required output } } fclose($handle); } else { // error while opening file. echo "error"; } 
0
source

Source: https://habr.com/ru/post/1487210/


All Articles