I have a text file with 8-10 words in each line with sequence no.and spaces. e.g 1)word 2)word 3)word 4)word ......... and i want to read it in an one dimensional array only words not sequence no.
A:
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)" )
Deniss Kozlovs
2010-01-06 10:41:16
+3
A:
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:
Array
(
[0] => First
[1] => Second
[2] => Third
[3] => Fourth
[4] => Fifth
[6] => Sixth
)
duckyflip
2010-01-06 10:44:26
Brilliant solution.
Deniss Kozlovs
2010-01-06 10:48:33
Another possible regex would be #(?<=\b)([A-Za-z]+)(?=\b)#. It matches all words regardless of any surrounding numbers, brackets, etc.
Techpriester
2010-01-06 10:48:38
A:
Assuming file contents is just like what duckyflip illustrated, another possible way
$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
)
ghostdog74
2010-01-06 11:28:34