Forum Moderators: coopster
I've got a set of headlines and accompanying stories stored in a text file. The file looks like this:
++ Headline 1
A few lines of text
++ Headline 2
A few lines of text
++ Headline 3
A few lines of text
++ Headline 4
A few lines of text
(etc. etc.)
What I need to do is end up with an array of the first three headlines from the page, without the plus signs before, so I can display them on another page of the site.
I know I can use fopen to open the file, substr($value,0,3); to remove the plus signs, but I'm not sure of the best procedure for putting it all together.
How would you go about ths process in the simplest way? (Pseudo code would be just fine - I can look up the functions, I just need to get the logic!)
Many thanks!
- no promises the regex will work, you probably need to escape them plus signs, that'd give you:
$matches = preg_match('#^\+\+([.]*)$', $file); instead.
<?php
$file = file_get_contents($_SERVER["DOCUMENT_ROOT"].'/data/file.txt');
$headlines = explode("\n++ ", $file);
$result = preg_match("/(.*?)\n(.*)/",$headlines);
echo $result[0];
echo "<br>";
echo $result[1];
echo "<br>";
echo $result[2];
?>
It seems to block with the
preg_match, which I seem to have got wrong. If I just echo $headlines, I get the array printed OK, but with all the text on the intermediate lines (which is what the preg_match is supposed to stop)... With the preg_match, I get nothing. One other thing, I have some lines in the text file which start with three plus signs, followed by a space (+++ ): is it possible to select only those lines which start with 2 plus signs followed by a space?
I altered the regex to look for a carriage return followed by two plus signs and a space:
preg_match("/\n\+\+ (.*?)\n.*?\n\+\+ (.*?)\n.*?\n\+\+ (.*?)\n/ms",$file,$headlines); That took care of the lines which start with three plus signs which matched the previous pattern.