/ Published in: PHP
Takes a string (from textarea, et alii) and turns it into formatted HTML.\\\\r\\\\n\\\\r\\\\nLines of text are turned into paragraphs, unless they start with \\\\\\\"+\\\\\\\" (headline); \\\\\\\"-\\\\\\\" (unordered list); or \\\\\\\"n.\\\\\\\" (ordered list).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Takes a string and tries to format it into HTML, using start-of-line rules: - If the line starts with "+" it is transformed into <h2> - If the line starts with "-" it is transformed into <ul>...</ul> - If the line starts with "N." it is transformed into <ol>...</ol> - If the line starts with anything else it is transformed into <p> */ class InputToHTML { /* A few variables. Set to private because there is no reason to see or access them. Simply change "private" to "public" if you are debugging... */ /* Processes text, indent optional */ public function process($text, $indent=0) { /* If data is bad then abort */ $this->final = false; return false; endif; /* Collect initial data */ /* Go over each line separately */ foreach ($this->lines as $key => &$line): /* Trim the line */ /* If the value is empty continue*/ if (!$line) continue; /* If the first letter is + then it is a headline */ $this->lists(); $this->final[] = $this->indent . "<h2>$line</h2>"; /* If the first letter is - then it is an unordered list item */ $this->ul[] = "<li>$line</li>"; /* If the first letter is xx. then it is an ordered list item */ $this->ol[] = "<li>$line</li>"; /* Otherwise treat the value as a paragraph */ else: $this->lists(); $this->final[] = $this->indent . "<p>$line</p>"; endif; endforeach; } /* Maintanance of lists is partially deferred to this function for clarity. This function is called whenever a line is NOT identified as a list. If the list variable is set, then it means that the list has been discontinued. It rounds up the list items, adds them to the "final" variable, and resets the original list variable */ private function lists() { /* Grab a few things */ $ul =& $this->ul; $ol =& $this->ol; /* Abort if there is nothing to do... */ /* Grab a few more things */ $i =& $this->indent; /* Add contents to "final", and prep ul for reuse */ endif; /* Add contents to "final", and prep ol for reuse */ endif; } /* Assembles the HTML simply by imploding the final array */ public function out() { else return ''; } /* Over and out */ } // EXAMPLE $obj = new InputToHtml(); $obj->process('+Healine 1 This is a paragraph Another paragraph - Unordered list item 1 - Unordered list item 2 This is a paragraph + Headline 2 1. Ordered list item 1 2. Ordered list item 2 Paragraph...'); echo $obj->out(); /* Output: <h2>Healine 1</h2> <p>This is a paragraph</p> <p>Another paragraph</p> <ul> <li>Unordered list item 1</li> <li>Unordered list item 2</li> </ul> <p>This is a paragraph</p> <h2> Headline 2</h2> <ol> <li>Ordered list item 1</li> <li>Ordered list item 2</li> </ol> <p>Paragraph...</p> */