Get N-Grams from strings and/or arrays.
PHP N-Grams library
In the fields of computational linguistics and probability, an n-gram is a contiguous sequence of n items from a given sample of text or speech. The items can be phonemes, syllables, letters, words or base pairs according to the application. The n-grams typically are collected from a text or speech corpus. When the items are words, n-grams may also be called shingles.
An n-gram of size 1 is referred to as a "unigram"; size 2 is a "bigram" (or, less commonly, a "digram"); size 3 is a "trigram". Larger sizes are sometimes referred to by the value of n in modern language, e.g., "four-gram", "five-gram", and so on. (More on Wikipedia)
- PHP >= 7.0
Include this library in your project by doing:
composer require drupol/phpngrams
The library provides two classes:
and one trait:
Let's say you want to find all the N-Gram of size 3 of the string hello world:
$word = 'hello world'; $ngram = new \drupol\phpngrams\NGrams(); $ngrams = $ngram->ngrams($word, 3); print_r(iterator_to_array($ngrams)); /*  => hel  => ell  => llo  => lo  => o w  => wo  => wor  => orl  => rld */
Instead of using a string, you may also use an array as input.
$word = ['h', 'e', 'l', 'l', 'o']; $ngram = new \drupol\phpngrams\NGramsCyclic(); $ngrams = $ngram->ngrams($word, 3); print_r(iterator_to_array($ngrams)); /* Array (  => Array (  => h  => e  => l )  => Array (  => e  => l  => l )  => Array (  => l  => l  => o )  => Array (  => l  => o  => h )  => Array (  => o  => h  => e ) ) */
To reduce to the maximum the memory footprint, the library returns Generators, if you want to get the complete resulting array, use iterator_to_array().
The library provides and object Ngrams and a trait NgramsTrait. It's up to you to decide how you want to use the library.
Find the complete API documentation at https://not-a-number.io/phpngrams.
Every time changes are introduced into the library, Travis CI run the tests.
The library has tests written with PHPSpec.
Feel free to check them out in the
spec directory. Run
composer phpspec to trigger the tests.
PHPInfection is used to ensure that your code is properly tested, run
composer infection to test your code.
Feel free to contribute to this library by sending Github pull requests. I'm quite reactive :-)