Skip to content

Commit

Permalink
Merge pull request #41 from andrewnicols/imgAlt
Browse files Browse the repository at this point in the history
Supply the image alt text when converting images
  • Loading branch information
mtibben committed Oct 11, 2015
2 parents 0636687 + f0b207d commit dc89d6a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Html2Text.php
Expand Up @@ -67,6 +67,7 @@ class Html2Text
'/(<tr[^>]*>|<\/tr>)/i', // <tr> and </tr>
'/<td[^>]*>(.*?)<\/td>/i', // <td> and </td>
'/<span class="_html2text_ignore">.+?<\/span>/i', // <span class="_html2text_ignore">...</span>
'/<(img)[^>]*alt=\"([^>"]+)\"[^>]*>/i', // <img> with alt tag
);

/**
Expand Down Expand Up @@ -97,7 +98,8 @@ class Html2Text
"\n\n", // <table> and </table>
"\n", // <tr> and </tr>
"\t\t\\1\n", // <td> and </td>
"" // <span class="_html2text_ignore">...</span>
"", // <span class="_html2text_ignore">...</span>
'[\\2]', // <img> with alt tag
);

/**
Expand Down
42 changes: 42 additions & 0 deletions test/ImageTest.php
@@ -0,0 +1,42 @@
<?php

namespace Html2Text;

class ImageTest extends \PHPUnit_Framework_TestCase
{
public function testImageDataProvider() {
return array(
'Without alt tag' => array(
'html' => '<img src="http://example.com/example.jpg">',
'expected' => '',
),
'Without alt tag, wrapped in text' => array(
'html' => 'xx<img src="http://example.com/example.jpg">xx',
'expected' => 'xxxx',
),
'With alt tag' => array(
'html' => '<img src="http://example.com/example.jpg" alt="An example image">',
'expected' => '[An example image]',
),
'With alt, and title tags' => array(
'html' => '<img src="http://example.com/example.jpg" alt="An example image" title="Should be ignored">',
'expected' => '[An example image]',
),
'With alt tag, wrapped in text' => array(
'html' => 'xx<img src="http://example.com/example.jpg" alt="An example image">xx',
'expected' => 'xx[An example image]xx',
),
);
}

/**
* @dataProvider testImageDataProvider
*/
public function testImages($html, $expected)
{
$html2text = new Html2Text($html);
$output = $html2text->getText();

$this->assertEquals($expected, $output);
}
}

0 comments on commit dc89d6a

Please sign in to comment.