Guest
Public paste!

andriesss

By: a guest | Feb 3rd, 2010 | Syntax: PHP | Size: 1.55 KB | Hits: 307 | Expires: Never
Copy text to clipboard
  1. <?php
  2.  
  3. // @author Andries Seutens <andries@sanmax.be>
  4.  
  5. $html = file_get_contents('http://www.netlash.com');
  6. echo '<pre>'; echo htmlToText($html); echo '</pre>';
  7.  
  8. function htmlToText($html)
  9. {
  10.         // normalize newlines (windows vs unix)
  11.         $html = str_replace("%\r%", "\n", $html);
  12.         $html = preg_replace("%\n\n+%", "\n", $html);
  13.  
  14.         // remove javascript
  15.         $html = preg_replace('%<script[^>]*>.*?</script>%s', '', $html);
  16.  
  17.         // strip html tags, except for the ones we want to format
  18.         $html = strip_tags($html, '<img><p><li><ul><ol><h1><h2><h3>');
  19.  
  20.         // replace pictures with their alt tags
  21.         $html = preg_replace('%\<img[^>]*alt="(.*)".*/\>%isU', '$1', $html);
  22.        
  23.         $patterns = array(
  24.                 // match list items
  25.                 '%<li[^>]*>(.*?)</li>%sme',
  26.                        
  27.                 // match multiple empty lines & spaces
  28.                 '%\s{3,}%',
  29.                        
  30.                 // match heading tags
  31.                 '%<h[1-9][^>]*>(.*?)</h[1-9]>%sme',
  32.  
  33.                 // match lists
  34.                 '%<(?:u|o)l[^>]*>(.*?)</(?:u|o)l>%sme',
  35.  
  36.                 // match paragraphs
  37.                 '%<p[^>]*>(.*?)</p>%sme',
  38.         );
  39.  
  40.         $replace = array(
  41.                 // properly format list items
  42.                 "'\n- '. preg_replace('%\s{2,}%', ' ', '\\1')",
  43.  
  44.                 // replaces multiply empty lines with a single line
  45.                 "\n",
  46.  
  47.                 // properly format heading tags
  48.                 "'\n'.preg_replace('%\s{2,}%', ' ', '\\1')",
  49.  
  50.                 // properly format lists
  51.                 "preg_replace('%\s{2,}%', ' ', '\\1').'\n'",
  52.  
  53.                 // properly format paragraphs
  54.                 "preg_replace('%\s{2,}%', ' ', '\\1').'\n'",
  55.         );
  56.  
  57.         $html = preg_replace($patterns, $replace, $html);
  58.         $html = strip_tags($html); // strip any leftover tags
  59.  
  60.         return trim(html_entity_decode($html));
  61. }