lasserafn/php-string-script-language
Detect which writing system a string uses with a simple PHP API. Check if text contains Arabic, Latin, Cyrillic, Thai, Han/Chinese, Japanese (Hiragana/Katakana), and many more scripts via boolean helpers like StringScript::isThai($text).
Installation:
composer require lasserafn/php-string-script-language
Add to composer.json if not using autoloading:
"autoload": {
"psr-4": {
"App\\": "app/",
"Lasserafn\\StringScriptLanguage\\": "vendor/lasserafn/php-string-script-language/src/"
}
}
Run composer dump-autoload.
First Use Case: Detect the language of a string:
use Lasserafn\StringScriptLanguage\StringScriptLanguage;
$detector = new StringScriptLanguage();
$language = $detector->detectLanguage('Bonjour le monde!');
echo $language; // Outputs: "fr"
Where to Look First:
vendor/lasserafn/php-string-script-language/src/).StringScriptLanguage for core methods.Basic Detection:
$detector = new StringScriptLanguage();
$language = $detector->detectLanguage($string);
Supports strings in ISO 639-1 (e.g., en, fr, de).
Encoding Detection (if extended):
// Hypothetical: If encoding detection is added later
$encoding = $detector->detectEncoding($string);
Batch Processing:
$strings = ['Hello', 'Hola', 'Ciao'];
$languages = array_map([$detector, 'detectLanguage'], $strings);
// Output: ['en', 'es', 'it']
Integration with Laravel:
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(StringScriptLanguage::class);
}
// app/Facades/StringScriptLanguage.php
public static function detectLanguage($string) {
return app(StringScriptLanguage::class)->detectLanguage($string);
}
Middleware for Localization:
// app/Http/Middleware/DetectLanguage.php
public function handle($request, Closure $next) {
$language = app(StringScriptLanguage::class)->detectLanguage($request->input('content'));
app()->setLocale($language);
return $next($request);
}
User-Generated Content: Detect language of comments/reviews in real-time:
$commentLanguage = $detector->detectLanguage($request->comment);
$this->translateComment($commentLanguage, $request->comment);
SEO/Content Analysis: Analyze blog posts or product descriptions:
$postLanguage = $detector->detectLanguage($post->content);
$this->indexPostForSearch($postLanguage, $post);
Multilingual APIs: Route requests based on detected language:
$language = $detector->detectLanguage($request->body);
return redirect()->route("content.$language");
Caching Results: Cache detected languages to avoid redundant processing:
$cacheKey = 'language_'.md5($string);
$language = cache()->remember($cacheKey, now()->addHours(1), function() use ($detector, $string) {
return $detector->detectLanguage($string);
});
Fallback Logic: Combine with Laravel’s locale fallbacks:
$language = $detector->detectLanguage($string) ?: config('app.fallback_locale');
Testing: Mock the detector in unit tests:
$mockDetector = Mockery::mock(StringScriptLanguage::class);
$mockDetector->shouldReceive('detectLanguage')->andReturn('fr');
$this->app->instance(StringScriptLanguage::class, $mockDetector);
False Positives:
"Ok") may return ambiguous results.if (strlen($string) < 5) {
return config('app.fallback_locale');
}
Non-Latin Scripts:
symfony/intl for multilingual support.Performance:
Encoding Issues:
$normalized = mb_convert_encoding($string, 'UTF-8');
Undocumented Methods:
Log Detection Results:
\Log::debug('Detected language', ['string' => $string, 'language' => $language]);
Test Edge Cases:
$this->assertEquals('en', $detector->detectLanguage('Hello 123!'));
$this->assertNull($detector->detectLanguage('')); // Handle null/undefined
Compare with Other Libraries:
google/cloud-translate or symfony/intl for accuracy.Extend the Detector: Add custom rules for domain-specific languages:
class CustomStringScriptLanguage extends StringScriptLanguage {
protected function getCustomRules() {
return [
'jp' => ['/^こんにちは$/u', '/^ありがとう$/u'],
];
}
}
Combine with Laravel Localization: Use detected languages to set the app locale:
$language = $detector->detectLanguage($string);
app()->setLocale($language);
Localization Fallbacks:
Configure a fallback chain in config/app.php:
'fallback_locale' => 'en',
'locale_fallbacks' => [
'fr' => ['en'],
'de' => ['en'],
],
Document Assumptions: Clearly document in your codebase that the detector is not 100% accurate and may require manual review for critical use cases (e.g., legal documents).
Monitor Accuracy: Track detection accuracy over time and retrain/customize rules as needed:
// Pseudocode for tracking
$stats = [
'total' => 0,
'correct' => 0,
];
$stats['total']++;
if ($detected === $expected) $stats['correct']++;
How can I help you explore Laravel packages today?