Posted By

yuconner on 01/03/08


Tagged

text Converter


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

marcio
vali29
DeadLy
jamesming


html2text


 / Published in: PHP
 

URL: http://sb2.info/php-script-html-plain-text-convert/

  1. function html2text($html)
  2. {
  3. $tags = array (
  4. 0 => '~<h[123][^>]+>~si',
  5. 1 => '~<h[456][^>]+>~si',
  6. 2 => '~<table[^>]+>~si',
  7. 3 => '~<tr[^>]+>~si',
  8. 4 => '~<li[^>]+>~si',
  9. 5 => '~<br[^>]+>~si',
  10. 6 => '~<p[^>]+>~si',
  11. 7 => '~<div[^>]+>~si',
  12. );
  13. $html = preg_replace($tags,"\n",$html);
  14. $html = preg_replace('~</t(d|h)>\s*<t(d|h)[^>]+>~si',' - ',$html);
  15. $html = preg_replace('~<[^>]+>~s','',$html);
  16. // reducing spaces
  17. $html = preg_replace('~ +~s',' ',$html);
  18. $html = preg_replace('~^\s+~m','',$html);
  19. $html = preg_replace('~\s+$~m','',$html);
  20. // reducing newlines
  21. $html = preg_replace('~\n+~s',"\n",$html);
  22. return $html;
  23. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: nigelnquande on December 15, 2014

The above function does not handle tables, images or links properly. Here follows a version I wrote (although it needs improvement for reducing duplicate blank lines):

function html2text ($html) { $plainmessage = strreplace(array('', '', '

', '

', ''), "\n", $html); $plainmessage = strreplace(array("", ""), "\n============", $plainmessage); $plainmessage = strreplace("", "| ", $plainmessage); $plainmessage = strreplace("", "\n-------------", $plainmessage); $plainmessage = strreplace(array("", ''), "# ", $plainmessage); $plainmessage = strreplace(array(''), " | ", $plainmessage); $plainmessage = str_replace(array('', ''), '__', $plain_message); $plain_message = str_replace(array('', ''), '_', $plain_message); $plain_message = str_replace(array('<a href="',>'), ']', $plain_message); $plain_message = strip_tags($plain_message); $plain_message = str_replace(" ", ' ', $plain_message);

    return $plain_message ;
}

You need to login to post a comment.