PHP code example of drupol / phpngrams

1. Go to this page and download the library: Download drupol/phpngrams library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

drupol / phpngrams example snippets




declare(strict_types = 1);

namespace drupol\phpngrams\tests;

use drupol\phpngrams\NGrams;
use drupol\phpngrams\NGramsCyclic;

string);

$ngrams = (new NGrams())->ngrams($chars, 3);

print_r(iterator_to_array($ngrams));
/*
[
    0 =>
        [
            0 => 'h',
            1 => 'e',
            2 => 'l',
        ],
    1 =>
        [
            0 => 'e',
            1 => 'l',
            2 => 'l',
        ],
    2 =>
        [
            0 => 'l',
            1 => 'l',
            2 => 'o',
        ],
    3 =>
        [
            0 => 'l',
            1 => 'o',
            2 => ' ',
        ],
    4 =>
        [
            0 => 'o',
            1 => ' ',
            2 => 'w',
        ],
    5 =>
        [
            0 => ' ',
            1 => 'w',
            2 => 'o',
        ],
    6 =>
        [
            0 => 'w',
            1 => 'o',
            2 => 'r',
        ],
    7 =>
        [
            0 => 'o',
            1 => 'r',
            2 => 'l',
        ],
    8 =>
        [
            0 => 'r',
            1 => 'l',
            2 => 'd',
        ],
];
*/

$string = 'hello world';

// Better use preg_split() than str_split() in case of UTF8 strings.
$chars = preg_split('/(?!^)(?=.)/u', $string);

$ngrams = (new NGramsCyclic())->ngrams($chars, 3);

print_r(iterator_to_array($ngrams));
/*
[
    0 => [
            0 => 'h',
            1 => 'e',
            2 => 'l',
        ],
    1 => [
            0 => 'e',
            1 => 'l',
            2 => 'l',
        ],
    2 => [
            0 => 'l',
            1 => 'l',
            2 => 'o',
        ],
    3 => [
            0 => 'l',
            1 => 'o',
            2 => ' ',
        ],
    4 => [
            0 => 'o',
            1 => ' ',
            2 => 'w',
        ],
    5 => [
            0 => ' ',
            1 => 'w',
            2 => 'o',
        ],
    6 => [
            0 => 'w',
            1 => 'o',
            2 => 'r',
        ],
    7 => [
            0 => 'o',
            1 => 'r',
            2 => 'l',
        ],
    8 => [
            0 => 'r',
            1 => 'l',
            2 => 'd',
        ],
    9 => [
            0 => 'l',
            1 => 'd',
            2 => 'h',
        ],
    10 => [
            0 => 'd',
            1 => 'h',
            2 => 'e',
        ],
];
*/