3 /*************************************************************************
5 * class.html2text.inc *
7 *************************************************************************
9 * Converts HTML to formatted plain text *
11 * Copyright (c) 2005 Jon Abernathy <jon@chuggnutt.com> *
12 * All rights reserved. *
14 * This script is free software; you can redistribute it and/or modify *
15 * it under the terms of the GNU General Public License as published by *
16 * the Free Software Foundation; either version 2 of the License, or *
17 * (at your option) any later version. *
19 * The GNU General Public License can be found at *
20 * http://www.gnu.org/copyleft/gpl.html. *
22 * This script is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * Author(s): Jon Abernathy <jon@chuggnutt.com> *
29 * Last modified: 04/06/05 *
30 * Modified: 2004/05/19 (tbr) *
32 *************************************************************************/
36 * Takes HTML and converts it to formatted, plain text.
38 * Thanks to Alexander Krug (http://www.krugar.de/) to pointing out and
39 * correcting an error in the regexp search array. Fixed 7/30/03.
41 * Updated set_html() function's file reading mechanism, 9/25/03.
43 * Thanks to Joss Sanglier (http://www.dancingbear.co.uk/) for adding
44 * several more HTML entity codes to the $search and $replace arrays.
47 * Thanks to Darius Kasperavicius (http://www.dar.dar.lt/) for
48 * suggesting the addition of $allowed_tags and its supporting function
49 * (which I slightly modified). Updated 3/12/04.
51 * Thanks to Justin Dearing for pointing out that a replacement for the
52 * <TH> tag was missing, and suggesting an appropriate fix.
55 * Thanks to Mathieu Collas (http://www.myefarm.com/) for finding a
56 * display/formatting bug in the _build_link_list() function: email
57 * readers would show the left bracket and number ("[1") as part of the
58 * rendered email address.
61 * Thanks to Wojciech Bajon (http://histeria.pl/) for submitting code
62 * to handle relative links, which I hadn't considered. I modified his
63 * code a bit to handle normal HTTP links and MAILTO links. Also for
64 * suggesting three additional HTML entity codes to search for.
67 * Thanks to Jacob Chandler for pointing out another link condition
68 * for the _build_link_list() function: "https".
71 * @author Jon Abernathy <jon@chuggnutt.com>
79 * Contains the HTML content to convert.
87 * Contains the converted, formatted text.
95 * Maximum width of the formatted text, in columns.
103 * List of preg* regular expression patterns to search for,
104 * used in conjunction with $replace.
111 "/\r/", // Non-legal carriage return
112 "/[\n\t]+/", // Newlines and tabs
113 '/<script[^>]*>.*?<\/script>/i', // <script>s -- which strip_tags supposedly has problems with
114 //'/<!-- .* -->/', // Comments -- which strip_tags might have problem a with
115 '/<a [^>]*href=("|\')([^"\']+)\1[^>]*>(.+?)<\/a>/ie', // <a href="">
116 '/<h[123][^>]*>(.+?)<\/h[123]>/ie', // H1 - H3
117 '/<h[456][^>]*>(.+?)<\/h[456]>/ie', // H4 - H6
118 '/<p[^>]*>/i', // <P>
119 '/<br[^>]*>/i', // <br>
120 '/<b[^>]*>(.+?)<\/b>/ie', // <b>
121 '/<i[^>]*>(.+?)<\/i>/i', // <i>
122 '/(<ul[^>]*>|<\/ul>)/i', // <ul> and </ul>
123 '/(<ol[^>]*>|<\/ol>)/i', // <ol> and </ol>
124 '/<li[^>]*>/i', // <li>
125 '/<hr[^>]*>/i', // <hr>
126 '/(<table[^>]*>|<\/table>)/i', // <table> and </table>
127 '/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
128 '/<td[^>]*>(.+?)<\/td>/i', // <td> and </td>
129 '/<th[^>]*>(.+?)<\/th>/ie', // <th> and </th>
153 * List of pattern replacements corresponding to patterns searched.
155 * @var array $replace
159 var $replace = array(
160 '', // Non-legal carriage return
161 ' ', // Newlines and tabs
162 '', // <script>s -- which strip_tags supposedly has problems with
163 //'', // Comments -- which strip_tags might have problem a with
164 '$this->_build_link_list("\\2", "\\3")', // <a href="">
165 "strtoupper(\"\n\n\\1\n\n\")", // H1 - H3
166 "ucwords(\"\n\n\\1\n\")", // H4 - H6
169 'strtoupper("\\1")', // <b>
171 "\n\n", // <ul> and </ul>
172 "\n\n", // <ol> and </ol>
174 "\n-------------------------\n", // <hr>
175 "\n\n", // <table> and </table>
176 "\n", // <tr> and </tr>
177 "\t\t\\1\n", // <td> and </td>
178 "strtoupper(\"\t\t\\1\n\")", // <th> and </th>
202 * Contains a list of HTML tags to allow in the resulting text.
204 * @var string $allowed_tags
206 * @see set_allowed_tags()
208 var $allowed_tags = '';
211 * Contains the base URL that relative links should resolve to.
219 * Indicates whether content in the $html variable has been converted yet.
221 * @var boolean $converted
225 var $_converted = false;
228 * Contains URL addresses from links to be rendered in plain text.
230 * @var string $link_list
232 * @see _build_link_list()
234 var $_link_list = array();
237 * Boolean flag, true if a table of link URLs should be listed after the text.
239 * @var boolean $_do_links
243 var $_do_links = true;
248 * If the HTML source string (or file) is supplied, the class
249 * will instantiate with that source propagated, all that has
250 * to be done it to call get_text().
252 * @param string $source HTML content
253 * @param boolean $from_file Indicates $source is a file to pull content from
254 * @param boolean $do_link_table indicate whether a table of link URLs is desired
258 function html2text( $source = '', $from_file = false, $produce_link_table = true )
260 if ( !empty($source) ) {
261 $this->set_html($source, $from_file);
263 $this->set_base_url();
264 $this->_do_links = $produce_link_table;
268 * Loads source HTML into memory, either from $source string or a file.
270 * @param string $source HTML content
271 * @param boolean $from_file Indicates $source is a file to pull content from
275 function set_html( $source, $from_file = false )
277 $this->html = $source;
279 if ( $from_file && file_exists($source) ) {
280 $fp = fopen($source, 'r');
281 $this->html = fread($fp, filesize($source));
285 $this->_converted = false;
289 * Returns the text, converted from HTML.
296 if ( !$this->_converted ) {
304 * Prints the text, converted from HTML.
309 function print_text()
311 print $this->get_text();
315 * Alias to print_text(), operates identically.
323 print $this->get_text();
327 * Sets the allowed HTML tags to pass through to the resulting text.
329 * Tags should be in the form "<p>", with no corresponding closing tag.
334 function set_allowed_tags( $allowed_tags = '' )
336 if ( !empty($allowed_tags) ) {
337 $this->allowed_tags = $allowed_tags;
342 * Sets a base URL to handle relative links.
347 function set_base_url( $url = '' )
350 $this->url = 'http://' . $_SERVER['HTTP_HOST'];
352 // Strip any trailing slashes for consistency (relative
353 // URLs may already start with a slash like "/file.html")
354 if ( substr($url, -1) == '/' ) {
355 $url = substr($url, 0, -1);
362 * Workhorse function that does actual conversion.
364 * First performs custom tag replacement specified by $search and
365 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
366 * and newlines to a readable format, and word wraps the text to
374 // Variables used for building the link list
376 //$this->_link_list = '';
378 $text = trim(stripslashes($this->html));
380 // Run our defined search-and-replace
381 $text = preg_replace($this->search, $this->replace, $text);
383 // Strip any other HTML tags
384 $text = strip_tags($text, $this->allowed_tags);
386 // Bring down number of empty lines to 2 max
387 $text = preg_replace("/\n\s+\n/", "\n", $text);
388 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
391 if ( sizeof($this->_link_list) ) {
392 $text .= "\n\nLinks:\n------\n";
393 foreach ($this->_link_list as $id => $link) {
394 $text .= '[' . ($id+1) . '] ' . $link . "\n";
398 // Wrap the text to a readable format
399 // for PHP versions >= 4.0.2. Default width is 75
400 $text = wordwrap($text, $this->width);
404 $this->_converted = true;
408 * Helper function called by preg_replace() on link replacement.
410 * Maintains an internal list of links to be displayed at the end of the
411 * text, with numeric indices to the original point in the text they
412 * appeared. Also makes an effort at identifying and handling absolute
413 * and relative links.
415 * @param integer $link_count Counter tracking current link number
416 * @param string $link URL of the link
417 * @param string $display Part of the text to associate number with
421 function _build_link_list($link, $display)
423 if (! $this->_do_links) return $display;
425 $link_lc = strtolower($link);
427 if (substr($link_lc, 0, 7) == 'http://' || substr($link_lc, 0, 8) == 'https://' || substr($link_lc, 0, 7) == 'mailto:')
434 if ($link{0} != '/') {
440 $index = array_search($url, $this->_link_list);
443 $index = sizeof($this->_link_list);
444 $this->_link_list[$index] = $url;
447 return $display . ' [' . ($index+1) . ']';