Friday, 10 August 2018

Convert HTML To ASCII With PHP

The reverse of turning ASCII text into HTML is to convert HTML into ASCII. And to this end here is a little function that does this.
  1. function html2ascii($s){
  2. // convert links
  3. $s = preg_replace('/]*)"?[^>]*>(.*?)/i','$2 ($1)',$s);
  4.  
  5. // convert p, br and hr tags
  6. $s = preg_replace('@]*>@i',"\n",$s);
  7. $s = preg_replace('@]*>@i',"\n\n",$s);
  8. $s = preg_replace('@]*>(.*)@i',"\n".'$1'."\n",$s);
  9.  
  10. // convert bold and italic tags
  11. $s = preg_replace('@]*>(.*?)@i','*$1*',$s);
  12. $s = preg_replace('@]*>(.*?)@i','*$1*',$s);
  13. $s = preg_replace('@]*>(.*?)@i','_$1_',$s);
  14. $s = preg_replace('@]*>(.*?)@i','_$1_',$s);
  15.  
  16. // decode any entities
  17. $s = strtr($s,array_flip(get_html_translation_table(HTML_ENTITIES)));
  18.  
  19. // decode numbered entities
  20. $s = preg_replace('/(\d+);/e','chr(str_replace(";","",str_replace("","","$0")))',$s);
  21.  
  22. // strip any remaining HTML tags
  23. $s = strip_tags($s);
  24.  
  25. // return the string
  26. return $s;
  27. }
To use this function just pass it a string. Here is an example of it at work.
  1. $htmlString = '<p>This is some <strong>XHTML</strong> markup that <em>will</em> be<br />turned <a href="http://www.hashbangcode.com/" title="#! code">into</a> an ascii string</p>';
  2.  
  3. echo html2ascii($htmlString);
Produces the following output.
  1. This is some *XHTML* markup that _will_ be
  2. turned into (http://www.hashbangcode.com/) an ascii string

0 comments:

Post a Comment