How to detect language from string in Laravel?
Hello Artisans,
In this tutorial, I'm going to show you how to detect language from string in Laravel? Today, you will learn how to detect language from a user given input in Laravel? This tutorial goes into details on how to check the language of user-given input in Laravel?
So let's get started on detecting language from strings.
Install composer package
First of all, you have to install a composer package to detect language from string easily. Just run the following composer command:
composer require patrickschur/language-detection
How to detect language?
Now you have to add namespace LanguageDetection\Language
at the top of your file to use language detection methods.
use LanguageDetection\Language;
Use the following method to detect language from string in PHP or Laravel. The input text should have at least a few sentences to detect the language correctly.
$ld = new Language;
$language = $ld->detect('Hallo hoe is het?')->close();
It will return an array of possible languages like this:
array(
"nl" => 0.66193548387097,
"af" => 0.51338709677419,
"br" => 0.49634408602151,
"nb" => 0.48849462365591,
"nn" => 0.48741935483871,
"fy" => 0.47822580645161,
"dk" => 0.47172043010753,
"sv" => 0.46408602150538,
"bi" => 0.46021505376344,
"de" => 0.45903225806452,
[...]
)
You can use the following method to get the exact language of a given string.
$language = $ld->detect('Hallo hoe is het?')->bestResults()->close();
It will give you a best match language for your given input text.
array(
"nl" => 0.66193548387097
)
Now you can use it in your condition.
if($language == 'nl'){
// do somthing
}
I hope it will help you.
Happy Coding :)