sashabo/shortener
最新稳定版本:1.2
Composer 安装命令:
composer require sashabo/shortener
包简介
Shortens plain text or html to the $length, preventing braking words and tags.
README 文档
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 }
统计信息
- 总下载量: 6.45k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: GPL-3.0-only
- 更新时间: 2023-10-21