weblib MDL-22664 html_to_text should not strip images, it should replace them by their alt text.

Also, an new optional argument to html_to_text to control word-wrapping.
This commit is contained in:
Tim Hunt
2010-08-04 17:39:56 +00:00
parent 791325ae6c
commit f47906fbf5
4 changed files with 47 additions and 5 deletions
+4 -1
View File
@@ -219,7 +219,7 @@ class html2text
'-',
'*',
'£',
'EUR', // Euro sign. € ?
'EUR', // Euro sign. € ?
' ' // Runs of spaces, post-handling
);
@@ -237,6 +237,7 @@ class html2text
'/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
// <a href="">
'/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
'/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt
);
/**
@@ -574,6 +575,8 @@ class html2text
return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
case 'a':
return $this->_build_link_list($matches[3], $matches[4]);
case 'img':
return '[' . $matches[2] . ']';
}
}
+25
View File
@@ -36,3 +36,28 @@ instead of:
-- Francois Marier <[email protected]> 2009-05-22
2- Don't just strip images, replace them with their alt text.
index b7e3e3e..96ef508 100644
--- a/lib/html2text.php
+++ b/lib/html2text.php
@@ -237,6 +237,7 @@ class html2text
'/<(a) [^>]*href=("|\')([^"\']+)\2[^>]*>(.*?)<\/a>/i',
// <a href="">
'/<(th)[^>]*>(.*?)<\/th>/i', // <th> and </th>
+ '/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt
);
/**
@@ -574,6 +575,8 @@ class html2text
return $this->_strtoupper("\n\n". $matches[2] ."\n\n");
case 'a':
return $this->_build_link_list($matches[3], $matches[4]);
+ case 'img':
+ return '[' . $matches[2] . ']';
}
}
-- Tim Hunt 2010-08-04
+13
View File
@@ -238,5 +238,18 @@ END;
$this->assertEqual($fast_enough, true, 'Timing test: ' . $new_time . 'secs (new) < ' . $old_time . 'secs (old)');
}
public function test_html_to_text_simple() {
$this->assertEqual("\n\n_Hello_ WORLD!", html_to_text('<p><i>Hello</i> <b>world</b>!</p>'));
}
public function test_html_to_text_image() {
$this->assertEqual('[edit]', html_to_text('<img src="edit.png" alt="edit" />'));
}
public function test_html_to_text_nowrap() {
$long = "Here is a long string, more than 75 characters long, since by default html_to_text wraps text at 75 chars.";
$this->assertEqual($long, html_to_text($long, 0));
}
}
?>
+5 -4
View File
@@ -2288,17 +2288,18 @@ function markdown_to_html($text) {
/**
* Given HTML text, make it into plain text using external function
*
* @uses $CFG
* @param string $html The text to be converted.
* @return string
* @param integer $width Width to wrap the text at. (optional, default 75 which
* is a good value for email. 0 means do not limit line length.)
* @return string plain text equivalent of the HTML.
*/
function html_to_text($html) {
function html_to_text($html, $width = 75) {
global $CFG;
require_once($CFG->libdir .'/html2text.php');
$h2t = new html2text($html);
$h2t = new html2text($html, false, true, $width);
$result = $h2t->get_text();
return $result;