Skip to content

Examples

Rumen Damyanov edited this page Dec 4, 2026 · 1 revision

Examples

These snippets use the same thresholds as the Rust crate. A decisive call returns one language. A close split returns every language that stayed above the noise floor.

Read the result three ways

IndexMode changes indexed() and the array returned by outcome() when the call is inconclusive. Build one detector per mode, because the config object is the one the detector keeps.

use Rumenx\PhpLangid\DetectorConfig;
use Rumenx\PhpLangid\IndexMode;
use Rumenx\PhpLangid\LanguageDetector;
use Rumenx\PhpLangid\ShareScale;

$text = file_get_contents('/notes/bilingual.txt');

$byLanguage = new LanguageDetector(
    (new DetectorConfig())->withIndexMode(IndexMode::Language)
);
$byShare = new LanguageDetector(
    (new DetectorConfig())->withIndexMode(IndexMode::Share)
);
$byOrder = new LanguageDetector(
    (new DetectorConfig())
        ->withIndexMode(IndexMode::Order)
        ->withShareScale(ShareScale::BasisPoints)
);

$language = $byLanguage->detect($text);
$share = $byShare->detect($text);
$order = $byOrder->detect($text);

// Decisive: the string "en".
// Inconclusive: ['en' => 52, 'fr' => 48]
$language->outcome();

// [[52, 'en'], [48, 'fr']]
$share->indexed();

// Basis points, highest share first.
// [
//   ['language' => 'en', 'name' => 'English', 'share' => 5159],
//   ['language' => 'fr', 'name' => 'French', 'share' => 4841],
// ]
$order->indexed();

Percent values are rounded and sum to 100. Basis points sum to 10000 and are the numbers the decisive check uses. Store basis points when a later job needs the exact split.

A label for a catalog

use Rumenx\PhpLangid\Detection;

function languageLabel(Detection $result): string
{
    if ($result->isDecisive()) {
        return $result->language()->code();
    }

    $codes = array_map(
        static fn ($language) => $language->code(),
        $result->languages()
    );

    return implode('+', $codes);
}

A clear English file becomes en. A half-and-half English and French file becomes en+fr. primary() is still available when a single best guess is required:

$bestGuess = $result->primary()->code();
$confident = $result->isDecisive();

Inventory a directory

$detector = new LanguageDetector();
$batch = $detector->detectDirectory('/documents');

$report = [];
foreach ($batch->files() as $file) {
    if (!$file->ok()) {
        $report[] = [
            'path' => $file->path(),
            'status' => $file->error()->reason(),
        ];
        continue;
    }

    $detection = $file->detection();
    $report[] = [
        'path' => $file->path(),
        'status' => $detection->isDecisive() ? 'language' : 'mixed',
        'language' => $detection->primary()->code(),
        'name' => $detection->primary()->name(),
        'share' => $detection->primary()->share(),
        'distribution' => $detection->indexed(),
    ];
}

file_put_contents(
    '/tmp/languages.json',
    json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);

detectDirectory('/documents', false) stays in that folder. Text files are scored. report.pdf and brief.docx are rows with status binary_document. A one-line note is text_too_short. Dotfiles and symbolic links are left out of the batch.

detected() and errors() are the same entries split by outcome:

foreach ($batch->detected() as $file) {
    echo $file->path(), ' ', $file->detection()->primary()->code(), PHP_EOL;
}

foreach ($batch->errors() as $file) {
    echo $file->path(), ' ', $file->error()->reason(), PHP_EOL;
}

Several paths, including ones that fail

$batch = $detector->detectPaths([
    '/documents/en.txt',
    '/documents/missing.txt',
    '/documents/scan.pdf',
]);

foreach ($batch->files() as $file) {
    echo $file->path(), ' ';
    echo $file->ok()
        ? $file->detection()->outcome()
        : $file->error()->reason();
    echo PHP_EOL;
}

One missing file does not stop the others. detectFile() throws, so use it when a missing path should abort the request.

HTML, with a script in another language

detect() strips scripts, styles, and tags when the string looks like HTML. A French script does not change an English page:

$html = <<<'HTML'
<!DOCTYPE html>
<html>
  <head>
    <script>
      Ceci est une phrase française assez longue pour dominer le document.
      Ceci est une phrase française assez longue pour dominer le document.
    </script>
  </head>
  <body>
    <p>The library reads each file and estimates which language the text is written in.
    A short quotation should not change the result when the rest of the page is consistent.
    This paragraph is about files, directories, and the language of the visible text.</p>
  </body>
</html>
HTML;

$result = (new LanguageDetector())->detect($html);
$result->isDecisive();       // true
$result->language()->code(); // en

detectFile('page.html') does the same strip because of the extension. XML is stripped too. Pass extracted PDF text to detect(); a .pdf path is binary_document.

Only the languages you ship

$detector = new LanguageDetector(
    (new DetectorConfig())->withOnlyLanguages(['EN', 'bg', 'fr', 'sv'])
);

$catalog = $detector->languages(); // the full 52, unchanged
$result = $detector->detect($text);

Codes are matched in lowercase. zz fails with unknown_language. English compared only with Bulgarian fails with no_classifiable_text, because the writing system has no selected language.

Keep a quotation in the distribution

The default margin is 15 points, so a page that is about 75% English and 25% French is still English. Widen the margin when that quotation should stay visible as a split:

$strict = new LanguageDetector(
    (new DetectorConfig())->withMinMargin(6000)
);

$result = $strict->detect($pageWithAFrenchQuote);
$result->isDecisive(); // false
$result->indexed();    // ['en' => 75, 'fr' => 25]

withMinShare(8000) requires the winner to reach 80% as well. Both checks run on basis points after the noise floor is applied.

Drop small shares

$detector = new LanguageDetector(
    (new DetectorConfig())
        ->withNoiseFloor(2000)
        ->withShareScale(ShareScale::BasisPoints)
);

$result = $detector->detect($mostlySwedish);
$result->shareOf('sv'); // 10000
$result->shareOf('nb'); // 0

Languages under the floor are removed, and the remaining shares are scaled to 100% before the decisive check. withMaxLanguages(2) then keeps the first two rows of indexed() and does not scale them again.

UTF-16 and a size limit

$detector = new LanguageDetector(
    (new DetectorConfig())->withMaxBytes(262144)
);

$result = $detector->detectFile('/imports/legacy-utf16.txt');

A leading FF FE or FE FF BOM is read as UTF-16. A UTF-8 BOM is skipped. A file over the byte limit throws file_too_large.

See Configuration, Files and directories, and Mixed languages.

Clone this wiki locally