Home  >  Article  >  Backend Development  >  How to split text into array using spaces in PHP

How to split text into array using spaces in PHP

巴扎黑
巴扎黑Original
2016-11-22 11:00:481524browse

PHP reads a text file line by line, then processes the space-delimited text and outputs it as an array.

Text document text.txt content:

1 Field 1 Field 2
2 Field 1 Field 2
3 Field 1 Field 2
4 Field 1 Field 2

Separate the text with spaces and use PHP to pass it through Process, the output is an array, the following is the code

$file = fopen("text.txt", "r") or exit("Unable to open file!");
while(!feof($ file))
{
$arr = split(' ', fgets($file));
print_r($arr);
}
fclose($file);
?>

Output result:

Array (
[0] => 1
[1] => Field 1
[2] => Field 2

)
Array (
[0] => 2
[1] => Field 1
[2] => Field 2

)
Array (
[0] => 3
[1] => Field 1
[2] => Field 2

)
Array (
[0 ] => 4
[1] => Field 1
[2] => Field 2
)

In this way, PHP uses spaces to divide text into arrays.

This php tutorial is provided by JS Code Station Produced by


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn