Recipe 13.12. Converting Plain Text to HTML

13.12.1. Problem

You want to turn plain text into reasonably formatted HTML.

13.12.2. Solution

First, encode entities with htmlentities( ). Then, transform the text into various HTML structures. The pc_text2html( ) function shown in Example 13-49 has basic transformations for links and paragraph breaks.

pc_text2html( )

<?php function pc_text2html($s) {   $s = htmlentities($s);   $grafs = split("\n\n",$s);   for ($i = 0, $j = count($grafs); $i < $j; $i++) {     // Link to what seem to be http or ftp URLs     $grafs[$i] = preg_replace('/((ht|f)tp:\/\/[^\s&]+)/',                               '<a href="$1">$1</a>',$grafs[$i]);     // Link to email addresses     $grafs[$i] = preg_replace('/[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}/i',         '<a href="mailto:$1">$1</a>',$grafs[$i]);     // Begin with a new paragraph     $grafs[$i] = '<p>'.$grafs[$i].'</p>';   }   return implode("\n\n",$grafs); } ?>

13.12.3. Discussion

The more you know about what the plain text looks like, the better your HTML conversion can be. For example, if emphasis is indicated with *asterisks* or /slashes/ around words, you can add rules that take care of that, as shown in Example 13-50.

More text-to-HTML rules

<?php $grafs[$i] = preg_replace('/(\A|\s)\*([^*]+)\*(\s|\z)/',                           '$1<b>$2</b>$3',$grafs[$i]); $grafs[$i] = preg_replace('{(\A|\s)/([^/]+)/(\s|\z)}',                           '$1<i>$2</i>$3',$grafs[$i]); ?>

13.12.4. See Also

Documentation on preg_replace( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: