C0ft C0ft - 1 month ago 8
JSON Question

Printing each line of a text file only after a certain word:

i have a text file that has the following formatting (with many more lines):



00:06:57 : Global: Andy: how is everyone today?
00:06:58 : Global: Ryan: pretty tired
00:07:00 : Global: Ben: meh the usual
00:07:01 : Global: Jim: average





What would be the best way to print or echo each line without the time or the global like:



Andy: how is everyone today?
Ryan: pretty tired
Ben: meh the usual
Jim: average





i tried



<?php
$file = 'chat.txt';
$searchfor = 'Global:';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '(.*)/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern(.*)\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
?>





but that comes up empty, should it be formatted into arrays or json to be handled better? thanks for your time

Answer

Try this

<?php
$file = 'chat.txt';


// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);

$pattern = "/..:..:.. : Global: /";
$replacement ="";

echo preg_replace($pattern, $replacement, $contents );

?>
Comments