swisnl/textsnippet

Create a snippet of text highlighting a given string

3.0.0 2020-04-22 07:43 UTC

This package is auto-updated.

Last update: 2024-04-07 18:06:13 UTC


README

Easy and fast way to create a snippet of text, for example for a search result. It will try and highlight the given words and give you the relevant text around it.

Build Status Latest Stable Version License Buy us a tree

Installation

Just use composer to install the package. Or download and include the TextSnipet.php file.

composer require swisnl/textsnippet

Examples

Some examples based on a 3 paragraph long Lorum ipsum text.

Basic usage

$snippet = new TextSnippet()
$snippet->createSnippet('Lorem', $lorumIpsum);

Will result in:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. ... Etiam bibendum lorem nec tempus sollicitudin. ... Sed in dapibus lorem. ... Nunc turpis ipsum, bibendum quis sodales sed, ullamcorper et lorem. Donec et metus hendrerit, interdum elit ut, dignissim dui.

Setting highlight html

You can set the tags surrounding the highlighted text. The %word% tag is required.

$snippet = new TextSnippet()
$snippet->setHighlightTemplate('<strong>%word%</strong>')

Setting min and max words

Setting min and maxwords tells the class to try and keep the number of words between the min and max.

// Defaults
$minWords = 30;
$maxWords = 100;

Setting min and max words.

$snippet = new TextSnippet()
$snippet->setMinWords(10);
$snippet->setMaxWords(30);

There is a known issue if you set min and max very close to eachother. It might not find the correct set of words/sentences to get exactly between the small gap.

Licence

The MIT License (MIT). Please see License File for more information.

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

SWIS ❤️ Open Source

SWIS is a web agency from Leiden, the Netherlands. We love working with open source software.