我有一个文本文件,每行8-10个单词,带有序列no.and空格。例如1)字2)字3)字4)字.........我想要在一维数组中读取它,只读单词,不读序列。
发布于 2010-01-06 18:44:26
假设您的文件如下所示:
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
)
发布于 2010-01-06 18:41:16
首先,如果每个单词都在新行上,那么就会先得到行:
$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”开头)
发布于 2010-01-06 19:28:34
假设文件内容就像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
)
https://stackoverflow.com/questions/2012207
复制相似问题