[英]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. 我有一个文本文件,每行有8-10个单词,序列号和空格。 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. 例如1)单词2)单词3)单词4)单词…………我想在一维数组中读它,只有单词而不是序列号。
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: 现在$matches[1]
将包含:
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)" ) (假设序列以“ x”开头)
Assuming file contents is just like what duckyflip illustrated, another possible way 假设文件内容就像duckyflip所示,另一种可能的方式
$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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.