我有一个文本文件,每行有8-10个单词,序列号和空格。 例如1)字2)字3)字4)字......... 我想在一维数组中读取它而不是序列号。
答案 0 :(得分:3)
假设您的文件如下所示:
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
)
答案 1 :(得分:0)
首先,如果你在新行上有每个单词,那么你首先得到行:
$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”开头)
答案 2 :(得分:0)
假设文件内容就像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
)