sashabo/shortener

Shortens plain text or html to the $length, preventing braking words and tags.

1.2 2024-03-05 09:59 UTC

This package is auto-updated.

Last update: 2024-11-05 11:22:19 UTC


README

Shortens plain text or html to the $length, preventing braking words and tags.

Shortening plain text

To cut plain text string to the $length use this static method:

Shortener::shortenText(string $source, int $length = 50, string $add = '...', bool $multiSpace = false): string

The shortener will never break a word, excepting the case if the first word is longer than $length. The shortener uses mb_strlen, not strlen, so it counts UTF-8 symbols correctly. If $multiSpace is true, the shortener counts each space (including \n, etc) as one symbol, otherwise a group of spaces is counted as 1 symbol.

For example, if the source is "Lorem ipsum dolor sit amet", here are lengths and results:

26: Lorem ipsum dolor sit amet (full string)

25: Lorem ipsum dolor sit...

10: Lorem...

6: Lor...

Those ... are counted too. So, the result string will have the required length including the length of $add

If you need to shorten one string few times, use this way for better performance:

$shortener = new TextShortener('Lorem ipsum dolor');
echo $shortener->shorten(10, '...');

So the source string will be parsed only once.

Shortening HTML

To cut HTML string to the $length use this static method:

Shortener::shortenHtml(string $source, int $length = 50, string $add = '...'): string

or:

$shortener = new HtmlShortener('<u>Lorem <i>ipsum</i> dolor sit amet</u>');
echo $shortener->shorten(26, '...');
echo $shortener->shorten(25, '...');
echo $shortener->shorten(10, '...');
echo $shortener->shorten(6, '...');

Results:

<u>Lorem <i>ipsum</i> dolor sit amet</u> (full string)
<u>Lorem <i>ipsum</i> dolor sit...</u>
<u>Lorem...</u>
<u>Lor...</u>

As you see, no closing tags are lost. If your source string is valid HTML, you will get valid HTML too.

HtmlShortener understands &xxx; symbols and count them as 1.

Using with Twig

The package contains ShortenerTwigExtension class providing shorten_text and shorten_html twig filters.

{{ 'Lorem ipsum dolor sit amet' | shorten_text(25, '...') }}

{{ '<u>Lorem <i>ipsum</i> dolor sit amet</u>' | shorten_html(25, '...') }}

To use them, just register the extension. For example, in Symfony add this to your config/services.yaml:

services:
    shortener_twig_extension:
        class: SashaBo\Shortener\Extras\ShortenerTwigExtension
        tags:
            - { name: twig.extension }