Skip to content

Commit

Permalink
Fix handling non-XML styled self-closing tags, closes #5
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcgrtz committed Dec 8, 2021
1 parent d78cf4e commit ce2c25b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Shorten.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@ final class Shorten
{
private const ENTITIES_PATTERN = '/&#?[a-zA-Z0-9]+;/i';
private const TAGS_AND_ENTITIES_PATTERN = '/<\/?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;/i';
private const SELF_CLOSING_TAGS = [
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'param',
'source',
'track',
'wbr',
'command',
'keygen',
'menuitem',
];

/**
* Safely truncate text containing markup.
Expand Down Expand Up @@ -92,6 +111,9 @@ public function truncateMarkup(
} elseif ($tag[mb_strlen($tag) - 2] === '/') {
// self-closing tag in XML dialect
$truncated .= $tag;
} elseif (in_array($tagName, self::SELF_CLOSING_TAGS)) {
// self-closing tag in non-XML dialect
$truncated .= $tag;
} else {
// opening tag
$truncated .= $tag;
Expand Down
18 changes: 18 additions & 0 deletions tests/ShortenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,22 @@ public function testTruncatesMarkupWithEmoji(): void
$shorten->truncateMarkup('<p>PHP 🐘 éléphant 🐘</p>', 4, '', true)
);
}

public function testTruncatesMarkupWithXMLStyledSelfClosingTags(): void
{
$shorten = new Shorten();
$this->assertEquals(
'<a href="https://example.com/">Go to<br />examp</a>…',
$shorten->truncateMarkup('<a href="https://example.com/">Go to<br />example site</a>', 10)
);
}

public function testTruncatesMarkupWithNonXMLStyledSelfClosingTags(): void
{
$shorten = new Shorten();
$this->assertEquals(
'<a href="https://example.com/"><img src="icon.gif" alt=""> Go to exa</a>…',
$shorten->truncateMarkup('<a href="https://example.com/"><img src="icon.gif" alt=""> Go to example site</a>', 10)
);
}
}

0 comments on commit ce2c25b

Please sign in to comment.