rumenx / php-langid
Detect the main language of a text, or return a percentage split when the result is too close to call.
Requires
- php: >=8.3
- ext-intl: *
- ext-mbstring: *
Requires (Dev)
- pestphp/pest: ^4.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 15:43:03 UTC
README
Identify the language of a text. A document that is clearly one language returns that language. When the leading languages are too close, the result is the distribution, with each language and its share.
The Rust crate with the same thresholds, profiles, and result rules is rumenx-langid.
Part of the langid family
- php-langid — PHP 8.3+ (this package)
- rust-langid — Rust crate
Composer name: rumenx/php-langid. Crate name: rumenx-langid.
What it measures
The score is the ranked character-trigram distance from Cavnar & Trenkle (1994), the method used by the PEAR package Text_LanguageDetect. Text is split into sentence-sized chunks. Each chunk votes for the closest language in the same writing system, weighted by how many letters it contains. The votes become shares.
A result is one language when the top share is at least 55% and it leads the next language by at least 15 percentage points. Both limits are basis points (5500 and 1500) and both can be changed. The check runs on basis points. Percent output is then rounded with the largest-remainder method, so a close split can display as 52 and 48 and still be inconclusive.
Profiles for 52 languages are built from public-domain Universal Declaration of Human Rights translations. The package reads text. It does not extract text from PDF or Office files. Pass the extracted text, or let a directory scan record those files as binary_document.
Installation
Requires PHP 8.3 or newer, with the intl and mbstring extensions.
composer require rumenx/php-langid
One language, or a split
use Rumenx\PhpLangid\LanguageDetector; $detector = new LanguageDetector(); $result = $detector->detectFile(__DIR__ . '/notes/sofia.txt'); if ($result->isDecisive()) { $language = $result->language(); echo $language->code(); // en echo $language->name(); // English echo $language->share(); // 100, meaning 100% } else { print_r($result->indexed()); // ['en' => 52, 'fr' => 48] }
outcome() returns the language code when the result is decisive, and the indexed distribution when it is not.
$outcome = $result->outcome(); // "en" // or ['en' => 52, 'fr' => 48]
primary() is the largest share even when the result is inconclusive. languages() is every language above the noise floor. shareOf('fr') reads one share in the configured scale.
How the distribution is indexed
use Rumenx\PhpLangid\DetectorConfig; use Rumenx\PhpLangid\IndexMode; use Rumenx\PhpLangid\ShareScale; $detector = new LanguageDetector( (new DetectorConfig()) ->withIndexMode(IndexMode::Share) ->withShareScale(ShareScale::Percent) ); print_r($detector->detect($mixed)->indexed()); // [[52, 'en'], [48, 'fr']]
| Mode | IndexMode |
Shape |
|---|---|---|
| Language code, then share | Language (default) |
['en' => 52, 'fr' => 48] |
| Share, then language code | Share |
[[52, 'en'], [48, 'fr']] |
| Rank order | Order |
[['language' => 'en', 'name' => 'English', 'share' => 52], ...] |
ShareScale::BasisPoints uses integers from 0 to 10000 that sum to 10000. ShareScale::Percent uses integers from 0 to 100 that sum to 100. withMaxLanguages(3) keeps the first rows and does not rescale them.
A directory of files
$batch = $detector->detectDirectory('/documents'); foreach ($batch->files() as $file) { if (!$file->ok()) { echo $file->path() . ' ' . $file->error()->reason() . PHP_EOL; continue; } $detection = $file->detection(); echo $file->path() . ' ' . $detection->primary()->code() . PHP_EOL; }
Text extensions are txt, md, markdown, html, htm, xhtml, xml, csv, json, rst, log, and text. HTML and XML are read with tags, scripts, and styles removed. UTF-8 and UTF-16 with a BOM are accepted.
pdf, doc, docx, rtf, odt, ppt, pptx, xls, and xlsx are reported as binary_document. Other extensions are omitted. Symbolic links and dotfiles are omitted. The default limit is 5 MiB per file and 5000 files in one directory. detectDirectory($path, false) stays in that directory.
detectPaths(['/a.txt', '/missing.txt']) keeps going when one path fails. The reason codes are text_too_short, no_classifiable_text, invalid_encoding, binary_document, file_not_found, file_too_large, unreadable, not_a_directory, not_a_file, invalid_path, invalid_config, unknown_language, and too_many_files.
Limit the languages
$detector = new LanguageDetector( (new DetectorConfig())->withOnlyLanguages(['en', 'bg', 'fr', 'sv']) );
An unknown code throws unknown_language. A text whose writing system is outside that set throws no_classifiable_text.
languages() lists the 52 shipped languages as code, name, and script.
Defaults
| Setting | Default | Meaning |
|---|---|---|
withMinShare |
5500 |
Top language must reach 55% |
withMinMargin |
1500 |
Lead over the second language, in basis points |
withNoiseFloor |
200 |
Drop languages under 2%, then rescale |
withMaxLanguages |
0 |
No cap |
withChunkChars |
280 |
Target letters in a chunk |
withMinChunkLetters |
50 |
Smaller trailing chunks merge backward |
withMinLetters |
40 |
Shorter text is text_too_short |
withMaxBytes |
5242880 |
File size limit |
withMaxFiles |
5000 |
Directory listing limit |
A 51% / 49% split stays a distribution with these defaults, because the lead is about 2 points and the margin is 15. Raise withMinMargin when a closer call should stay mixed. Lower it when a smaller lead should win.
Other packages
Development
composer test
composer analyze
composer style
composer quality
Guides
Longer examples are published on the project wiki:
- Examples — index modes, a directory report, HTML, an allow-list, basis points, and a wider margin
- Configuration
- Files
- Mixed-Language
- Quick-Start
License
MIT. See LICENSE.md.