Skip to content

Novis\Intl\Segmenter::words

Splits text into words, the way a language does, also for languages that write no spaces between words.

Segmenter::words takes a list of strings and returns one list of parts for each string, in the same order. Each part has a text and a wordLike flag. wordLike is true for a word or a number, such as "Shop", "It's" or "9.50". It is false for spaces and punctuation. All parts of a string, joined in order, give the string again.

Japanese and Chinese have no spaces between words. Segmenter::words uses a dictionary for them, so "東京で買い物" gives the three words "東京", "で" and "買い物". An empty string gives an empty list.

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

Good to know: to count the words of a text, count the parts where wordLike is true. To split a text into sentences, use Segmenter::sentences.

Parameters

  • $stringsarray<string>
  • $localestring

Return value

Returns array<array<{ text: string, wordLike: bool }>>.

Examples

Count the words

<?nvs
// Shows how to count the words of each text in a list.
use Novis\Intl\Segmenter;
array<string> $comments = ["Hello, Shop! It's 9.50 now.", 'Great blog', ''];
// A part counts when `wordLike` is `true`. Spaces and punctuation do not count.
// This prints 5, 2 and 0.
foreach (Segmenter::words($comments, 'en') as array<{ text: string, wordLike: bool }> $parts) {
uint $count = 0;
foreach ($parts as { text: string, wordLike: bool } $part) {
if ($part->wordLike) {
$count = $count + 1;
}
}
echo $count, "\n";
}
Output
5
2
0

Japanese has no spaces

<?nvs
// Shows how to split Japanese text into words, although it has no spaces between them.
use Novis\Intl\Segmenter;
array<{ text: string, wordLike: bool }> $parts = Segmenter::words(['東京で買い物'], 'ja')[0];
// This prints 東京 | で | 買い物.
array<string> $words = [];
foreach ($parts as { text: string, wordLike: bool } $part) {
$words[] = $part->text;
}
echo Core\Str::join($words, ' | '), "\n";
Output
東京 | で | 買い物

Mark each word

<?nvs
// Shows how to put brackets around each word and keep the spaces and punctuation as they are.
use Novis\Intl\Segmenter;
string $text = 'Open the Shop, then the Blog.';
// The parts joined in order give the text again. Here each word gets brackets.
// This prints [Open] [the] [Shop], [then] [the] [Blog].
string $marked = '';
foreach (Segmenter::words([$text], 'en')[0] as { text: string, wordLike: bool } $part) {
$marked = $marked . ($part->wordLike ? '[' . $part->text . ']' : $part->text);
}
echo $marked, "\n";
Output
[Open] [the] [Shop], [then] [the] [Blog].