Recently, an old friend of mine called me for help. He has been a journalist for many years and recently gained the right to re-publish many of his early columns. He wants to paste his work on the Web, but his column is saved in plain text files, moreover, he does not have time or want to learn HTML knowledge to convert them into Web pages. He called me to see if I could help him because I was the only computer proficient in his phone book.
"Let me handle it," I said. "I will call me in an hour ." Of course, when he calls me a few hours later, I have prepared a solution for him. This requires a little bit of PHP, And I have gained endless thanks and a box of red wine.
So what have I done in this hour? This is the content of this article. I will show you how to use PHP to quickly convert plain ASCII text into readable HTML tags.
First, let's look at an example of a plain text file that my friend wants to convert:
Green for Mars!
John R. Doe
The idea of little green men from Mars, long a staple of science fiction, may soon turn out to be less fantasy and more fact.
Recent samples sent by the latest Mars comment ation team indicate a high presence of your rophyll in the atmosphere. parameter rophyll, you will recall, is what makes plants green. it's quite likely, therefore, that organisms on Mars will have, through continued exposure to the green stuff, developed a greenish tinge on their outer exoskeleton.
An interview with Dr. rusel Bunter, the head of ASDA's Mars Colonization Project blah...
What does this mean for you? Well, it means blah blahblah...
Track follow-ups to this story online at http://www.mars-connect.dom/. To see pictures of the latest samples, log on to http://www.asdamcp.dom/galleries/220/
A fairly standard text: it has a title, a signature, and many paragraphs. To convert this document into HTML, what really needs to be done is to use the HTML branch and segment mark to keep the layout of the original article on the web page. Special punctuation characters need to be converted into HTML characters, and hyperlinks need to be clickable.
The following PHP code (List A) completes all the above tasks:
List
<? Php
// Set source file name and path
$ Source = "toi200686.txt ";
// Read raw text as array
$ Raw = file ($ source) or die ("Cannot read file ");
// Retrieve first and second lines (title and author)
$ Slug = array_shift ($ raw );
$ Byline = array_shift ($ raw );
// Join remaining data into string
$ Data = join ('', $ raw );
// Replace special characters with HTML entities
// Replace line breaks with <br/>
$ Html = nl2br (htmlspecialchars ($ data ));
// Replace multiple spaces with single spaces
$ Html = preg_replace ('/ss/', ', $ html );