Over a million developers have joined DZone.

Text To HTML Converter (PHP 4+)

DZone's Guide to

Text To HTML Converter (PHP 4+)

Free Resource
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.

  $part ){
    $parts[ $key ] = substr($string, $pos, strlen($part));
    $pos += strlen($part) + strlen($find);

  return( join( $replace, $parts ) );

function txt2html($txt) {
// Transforms txt in html

  //Kills double spaces and spaces inside tags.
  while( !( strpos($txt,'  ') === FALSE ) ) $txt = str_replace('  ',' ',$txt);
  $txt = str_replace(' >','>',$txt);
  $txt = str_replace('< ','<',$txt);

  //Transforms accents in html entities.
  $txt = htmlentities($txt);

  //We need some HTML entities back!
  $txt = str_replace('"','"',$txt);
  $txt = str_replace('<','<',$txt);
  $txt = str_replace('>','>',$txt);
  $txt = str_replace('&','&',$txt);

  //Ajdusts links - anything starting with HTTP opens in a new window
  $txt = stri_replace("


'; $html = str_replace("$eol","
\n",$html); $html = str_replace("


\n\n",$html); $html = str_replace("



",$html); //Wipes
after block tags (for when the user includes some html in the text). $wipebr = Array("table","tr","td","blockquote","ul","ol","li"); for($x = 0; $x < count($wipebr); $x++) { $tag = $wipebr[$x]; $html = stri_replace("<$tag>
","<$tag>",$html); $html = stri_replace("
"," ",$html); } return $html; } ?>

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}