繁体   English   中英

如何在PHP数组中逐字读取文本文件内容

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

我有一个文本文件,每行有8-10个单词,序列号和空格。 例如1)单词2)单词3)单词4)单词…………我想在一维数组中读它,只有单词而不是序列号。

假设您的文件如下所示:

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

使用此功能,您只能提取单词:

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

现在$matches[1]将包含:

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

首先,如果每个单词都在新行上,那么您将首先获得行:

$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); 
    }
}

(假设序列以“ x”开头)

假设文件内容就像duckyflip所示,另一种可能的方式

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

输出

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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