Skip to content

Novis\Intl\Segmenter::sentences

Splits text into sentences, the way a language does.

Segmenter::sentences takes a list of strings and returns one list of sentences for each string, in the same order. A sentence ends after a ".", "?" or "!" and the spaces that follow it. Each sentence keeps those spaces, so all sentences of a string, joined in order, give the string again. An empty string gives an empty list.

The rules know common cases. A number such as "3.5" does not end a sentence. Some short words do end one, so "Mr. Smith is here." gives two sentences: "Mr. " and "Smith is here.". Check the result when your text has many abbreviations.

Segmenter::sentences throws a LogicError when the locale tag is not valid.

Good to know: to split a text into words, use Segmenter::words.

Parameters

  • $stringsarray<string>
  • $localestring

Return value

Returns array<array<string>>.

Examples

Count the sentences

<?nvs
// Shows how to count the sentences of each text in a list.
use Novis\Intl\Segmenter;
array<string> $reviews = ['The Shop is open. Is the Blog? Yes!', 'Fast delivery.', ''];
// Each text gives one list of sentences. This prints 3, 1 and 0.
foreach (Segmenter::sentences($reviews, 'en') as array<string> $sentences) {
echo Core\Arr::count($sentences), "\n";
}
Output
3
1
0

A short preview

<?nvs
// Shows how to make a short preview of a text from its first sentence.
use Novis\Intl\Segmenter;
string $post = 'The Blog has a new page. It lists every product in the Shop.';
// A sentence keeps the space after it, so `Core\Str::trim` removes that space.
// This prints The Blog has a new page.
array<string> $sentences = Segmenter::sentences([$post], 'en')[0];
echo Core\Str::trim($sentences[0]), "\n";
Output
The Blog has a new page.

Numbers do not end a sentence

<?nvs
// Shows that a dot inside a number does not end a sentence.
use Novis\Intl\Segmenter;
array<string> $sentences = Segmenter::sentences(['The price is 3.50 euros. It was 4.20 before.'], 'en')[0];
// The text has two sentences. This prints each one between brackets.
// The first sentence keeps the space after it.
foreach ($sentences as string $sentence) {
echo '[', $sentence, "]\n";
}
Output
[The price is 3.50 euros. ]
[It was 4.20 before.]