Question

I am attempting to read a file on my server and then use regular expressions to determine what formatting each part of that text file should have when viewed within a web-browser. I am simply opening file.txt's contents and reading.

P.S. - I have no problem with creating and using CSS classes and would prefer to use them if possible from an external stylesheet.

I'm purely stuck on how to add the formatting to each individual part of the text file based on the rules from the regular expressions - does anyone have any suggestions for the PHP coding?

Primarily:
1.How to apply the regular expressions to each individual part of the whole text
2.How to apply the css rules in an external stylesheet (class1, class2, etc.) given by class name to above (see 1) specific part of the text

For example: (see sample of text file below if more clarity is required on the format / size of this)

Forcing any date such as 14.11.2013 - 23.51.40 to be formatted in an italic green font by using the following regular expression:

[0-9]+[.][0-9]+[.][0-9]+ - [0-9]+[.][0-9]+[.][0-9]+.

Then have upper-case words such as DELETE formatted differently in a bold red font from lower-case etc.

Sample of text:

This .txt file is around 1 Mb in size at the moment - however this changes each time the script that creates it is run.

14.11.2013 - 23.51.40 - START BACKUP LOG
14.11.2013 - 23.51.40 - INITIATE BACKUP PROCEDURE
14.11.2013 - 23.51.40 - DELETE previous backup log
Was it helpful?

Solution

The easiest thing to do would be to a preg_replace.

Something along these lines should work for you.

$date = "/[0-9]+[.][0-9]+[.][0-9]+ - [0-9]+[.][0-9]+[.][0-9]+/";
$keywords = array("/START/", "/INITIATE/", "/DELETE/");

$line = preg_replace($date, "<span class=\"date\">$0</span>", $line);
$line = preg_replace($keywords, "<span class=\"keyword\">$0</span>", $line);

That will surround the matches with span tags, which you can then style however you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top