Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Fabio FZero http://www.geradorzero.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Text to HTML converter (PHP 4+)

Simple function to convert a text into formatted HTML in PHP. The function implements some text cleanups (double space removal) and accepts some HTML in the text, like links (a href), lists (ul, ol), blockquotes and tables. This makes it perfect for use inside custom-made blogging engines and CMSs. There's also an implementation of case-insensitive search/replace for php < 5.

   1  
   2  <?php
   3  
   4  function stri_replace( $find, $replace, $string ) {
   5  // Case-insensitive str_replace()
   6  
   7    $parts = explode( strtolower($find), strtolower($string) );
   8  
   9    $pos = 0;
  10  
  11    foreach( $parts as $key=>$part ){
  12      $parts[ $key ] = substr($string, $pos, strlen($part));
  13      $pos += strlen($part) + strlen($find);
  14    }
  15  
  16    return( join( $replace, $parts ) );
  17  }
  18  
  19  
  20  function txt2html($txt) {
  21  // Transforms txt in html
  22  
  23    //Kills double spaces and spaces inside tags.
  24    while( !( strpos($txt,'  ') === FALSE ) ) $txt = str_replace('  ',' ',$txt);
  25    $txt = str_replace(' >','>',$txt);
  26    $txt = str_replace('< ','<',$txt);
  27  
  28    //Transforms accents in html entities.
  29    $txt = htmlentities($txt);
  30  
  31    //We need some HTML entities back!
  32    $txt = str_replace('&quot;','"',$txt);
  33    $txt = str_replace('&lt;','<',$txt);
  34    $txt = str_replace('&gt;','>',$txt);
  35    $txt = str_replace('&amp;','&',$txt);
  36  
  37    //Ajdusts links - anything starting with HTTP opens in a new window
  38    $txt = stri_replace("<a href=\"http://","<a target=\"_blank\" href=\"http://",$txt);
  39    $txt = stri_replace("<a href=http://","<a target=\"_blank\" href=http://",$txt);
  40  
  41    //Basic formatting
  42    $eol = ( strpos($txt,"\r") === FALSE ) ? "\n" : "\r\n";
  43    $html = '<p>'.str_replace("$eol$eol","</p><p>",$txt).'</p>';
  44    $html = str_replace("$eol","<br />\n",$html);
  45    $html = str_replace("</p>","</p>\n\n",$html);
  46    $html = str_replace("<p></p>","<p>&nbsp;</p>",$html);
  47  
  48    //Wipes <br> after block tags (for when the user includes some html in the text).
  49    $wipebr = Array("table","tr","td","blockquote","ul","ol","li");
  50  
  51    for($x = 0; $x < count($wipebr); $x++) {
  52  
  53      $tag = $wipebr[$x];
  54      $html = stri_replace("<$tag><br />","<$tag>",$html);
  55      $html = stri_replace("</$tag><br />","</$tag>",$html);
  56  
  57    }
  58  
  59    return $html;
  60  }
  61  
  62  ?>
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS