function to format text file to HTML with PHP

This function takes in a text document, and reformats it for use on an HTML page.

function processText($text) {       
        $text = str_replace(">", ">", $text);       
        $text = str_replace("&lt;", "<", $text);       
        $text = str_replace("\r\n\r\n", "\n", $text);       
        $text = str_replace("\r\n", "\n", $text);       
        $text = str_replace("\n\n", "\n", $text);       
        $text = str_replace("\n", " </p>\n<p> ", $text);       
        $text = "<p>".$text."</p>";       
        return $text;
}

Line by line, the process is:

Step 1

$text = str_replace("&gt;", ">", $text) and $text = str_replace("&lt;", "<", $text) – here each occurrence of “>” or “<” is replaced by it’s corresponding ASCII value (&gt; or &lt;).

Step 2

$text = str_replace("\r\n\r\n", "\n", $text) – here we replace “\r\n\r\n” double line breaks with a single “\n” line break (this is not HTML yet, but we will deal with this soon)

Step 3

$text = str_replace("\r\n", "\n", $text) – here we replace “\r\n” single line breaks with a single “\n” line break (again, this is not HTML yet, but we will deal with this)

Step 4

$text = str_replace("\n\n", "\n", $text) – here we replace “\n\n” double line breaks with a single “\n” line break (this is not HTML yet, but we are about to deal with this)

Step 5

$text = str_replace("\n", " </p>\n<p> ", $text) – here we replace “\n” single line breaks with a “</p>\n<p>” HTML paragraph break. As all other breaks have been converted to “\n” prior to this, they all become paragraphs

Step 6

$text = "<p>".$text."</p>" – this final line makes sure the text begins and ends with HTML paragraph tags.

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: