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="([^"]+)"[^>]*>(.+?)<\/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>/i', // <th> and </th>
154 * List of pattern replacements corresponding to patterns searched.
156 * @var array $replace
160 var $replace = array(
161 '', // Non-legal carriage return
162 ' ', // Newlines and tabs
163 '', // <script>s -- which strip_tags supposedly has problems with
164 //'', // Comments -- which strip_tags might have problem a with
165 '$this->_build_link_list("\\1", "\\2")', // <a href="">
166 "strtoupper(\"\n\n\\1\n\n\")", // H1 - H3
167 "ucwords(\"\n\n\\1\n\n\")", // H4 - H6
170 'strtoupper("\\1")', // <b>
172 "\n\n", // <ul> and </ul>
173 "\n\n", // <ol> and </ol>
175 "\n-------------------------\n", // <hr>
176 "\n\n", // <table> and </table>
177 "\n", // <tr> and </tr>
178 "\t\t\\1\n", // <td> and </td>
179 "strtoupper(\"\t\t\\1\n\")", // <th> and </th>
204 * Contains a list of HTML tags to allow in the resulting text.
206 * @var string $allowed_tags
208 * @see set_allowed_tags()
210 var $allowed_tags = '';
213 * Contains the base URL that relative links should resolve to.
221 * Indicates whether content in the $html variable has been converted yet.
223 * @var boolean $converted
227 var $_converted = false;
230 * Contains URL addresses from links to be rendered in plain text.
232 * @var string $link_list
234 * @see _build_link_list()
236 var $_link_list = array();
241 * If the HTML source string (or file) is supplied, the class
242 * will instantiate with that source propagated, all that has
243 * to be done it to call get_text().
245 * @param string $source HTML content
246 * @param boolean $from_file Indicates $source is a file to pull content from
250 function html2text( $source = '', $from_file = false )
252 if ( !empty($source) ) {
253 $this->set_html($source, $from_file);
255 $this->set_base_url();
259 * Loads source HTML into memory, either from $source string or a file.
261 * @param string $source HTML content
262 * @param boolean $from_file Indicates $source is a file to pull content from
266 function set_html( $source, $from_file = false )
268 $this->html = $source;
270 if ( $from_file && file_exists($source) ) {
271 $fp = fopen($source, 'r');
272 $this->html = fread($fp, filesize($source));
276 $this->_converted = false;
280 * Returns the text, converted from HTML.
287 if ( !$this->_converted ) {
295 * Prints the text, converted from HTML.
300 function print_text()
302 print $this->get_text();
306 * Alias to print_text(), operates identically.
314 print $this->get_text();
318 * Sets the allowed HTML tags to pass through to the resulting text.
320 * Tags should be in the form "<p>", with no corresponding closing tag.
325 function set_allowed_tags( $allowed_tags = '' )
327 if ( !empty($allowed_tags) ) {
328 $this->allowed_tags = $allowed_tags;
333 * Sets a base URL to handle relative links.
338 function set_base_url( $url = '' )
341 $this->url = 'http://' . $_SERVER['HTTP_HOST'];
343 // Strip any trailing slashes for consistency (relative
344 // URLs may already start with a slash like "/file.html")
345 if ( substr($url, -1) == '/' ) {
346 $url = substr($url, 0, -1);
353 * Workhorse function that does actual conversion.
355 * First performs custom tag replacement specified by $search and
356 * $replace arrays. Then strips any remaining HTML tags, reduces whitespace
357 * and newlines to a readable format, and word wraps the text to
365 // Variables used for building the link list
367 //$this->_link_list = '';
369 $text = trim(stripslashes($this->html));
371 // Run our defined search-and-replace
372 $text = preg_replace($this->search, $this->replace, $text);
374 // Strip any other HTML tags
375 $text = strip_tags($text, $this->allowed_tags);
377 // Bring down number of empty lines to 2 max
378 $text = preg_replace("/\n\s+\n/", "\n", $text);
379 $text = preg_replace("/[\n]{3,}/", "\n\n", $text);
382 if ( sizeof($this->_link_list) ) {
383 $text .= "\n\nLinks:\n------\n";
384 foreach ($this->_link_list as $id => $link) {
385 $text .= '[' . ($id+1) . '] ' . $link . "\n";
389 // Wrap the text to a readable format
390 // for PHP versions >= 4.0.2. Default width is 75
391 $text = wordwrap($text, $this->width);
395 $this->_converted = true;
399 * Helper function called by preg_replace() on link replacement.
401 * Maintains an internal list of links to be displayed at the end of the
402 * text, with numeric indices to the original point in the text they
403 * appeared. Also makes an effort at identifying and handling absolute
404 * and relative links.
406 * @param integer $link_count Counter tracking current link number
407 * @param string $link URL of the link
408 * @param string $display Part of the text to associate number with
412 function _build_link_list($link, $display)
414 $link_lc = strtolower($link);
416 if (substr($link_lc, 0, 7) == 'http://' || substr($link_lc, 0, 8) == 'https://' || substr($link_lc, 0, 7) == 'mailto:')
423 if ($link{0} != '/') {
429 $index = array_search($url, $this->_link_list);
432 $index = sizeof($this->_link_list);
433 $this->_link_list[$index] = $url;
436 return $display . ' [' . ($index+1) . ']';