PHP: How do I detect if an input string is Arabic

后端 未结 10 1374
旧时难觅i
旧时难觅i 2020-12-08 08:34

Is there a way to detect the language of the data being entered via the input field?

10条回答
  •  失恋的感觉
    2020-12-08 08:54

    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;
            }
        }
    

提交回复
热议问题