Is there a way to detect the language of the data being entered via the input field?
public static function isArabic($string){
if(preg_match('/\p{Arabic}/u', $string))
return true;
return false;
}
The PHP Text_LanguageDetect library is able to detect 52 languages. It's unit-tested and installable via composer and PEAR.
I'm not aware of a PHP solution for this, no.
The Google Translate Ajax APIs may be for you, though.
Check out this Javascript snippet from the API docs: Example: Language Detection
This function checks whether the entered line/sentence is arabic or not. I trimmed it first then check word by word calculating the total count for both.
function isArabic($string){
// Initializing count variables with zero
$arabicCount = 0;
$englishCount = 0;
// Getting the cleanest String without any number or Brackets or Hyphen
$noNumbers = preg_replace('/[0-9]+/', '', $string);
$noBracketsHyphen = array('(', ')', '-');
$clean = trim(str_replace($noBracketsHyphen , '', $noNumbers));
// After Getting the clean string, splitting it by space to get the total entered words
$array = explode(" ", $clean); // $array contain the words that was entered by the user
for ($i=0; $i <= count($array) ; $i++) {
// Checking either word is Arabic or not
$checkLang = preg_match('/\p{Arabic}/u', $array[$i]);
if($checkLang == 1){
++$arabicCount;
} else{
++$englishCount;
}
}
if($arabicCount >= $englishCount){
// Return 1 means TRUE i-e Arabic
return 1;
} else{
// Return 0 means FALSE i-e English
return 0;
}
}
You can use function, which i have written for you:
<?php
/**
* Return`s true if string contains only arabic letters.
*
* @param string $string
* @return bool
*/
function is_arabic($string)
{
return (preg_match("/^\p{Arabic}/i", $string) > 0);
}
But please, check it, before use.
[EDIT 1]
Your question: "How do I detect if an input string is Arabic?" And i have answered to it, what`s wrong?
[EDIT 2]
Read this - Detect language from string in PHP
[EDIT 3]
Excuse, i rewrite function to this, try it:
function is_arabic($subject)
{
return (preg_match("/^[\x0600-\x06FF]/i", $subject) > 0);
}
I assume you're referring to a Unicode string... in which case, just look for the presence of any character with a code between U+0600–U+06FF (1536–1791) in the string.