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

后端 未结 10 1400
旧时难觅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 09:04

    hmm i may offer an improved version of DimaKrasun's function:

    functoin is_arabic($string) {
        if($string === 'arabic') {
             return true;
        }
        return false;
    }
    

    okay, enough joking!

    Pekkas suggestion to use the google translate api is a good one! but you are relying on an external service which is always more complicated etc.

    i think Rushyos approch is good! its just not that easy. i wrote the following function for you but its not tested, but it should work...

         ".$pos.PHP_EOL;
    
            if($pos >= 1536 && $pos <= 1791) {
                $arabic_count++;
            } else if($pos > 123 && $pos < 123) {
                $latin_count++;
            }
            $total_count++;
        }
        if(($arabic_count/$total_count) > 0.6) {
            // 60% arabic chars, its probably arabic
            return true;
        }
        return false;
    }
    $arabic = is_arabic('عربية إخبارية تعمل على مدار اليوم. يمكنك مشاهدة بث القناة من خلال الموقع'); 
    var_dump($arabic);
    ?>
    

    final thoughts: as you see i added for example a latin counter, the range is just a dummy number b ut this way you could detect charsets (hebrew, latin, arabic, hindi, chinese, etc...)

    you may also want to eliminate some chars first... maybe @, space, line breaks, slashes etc... the PREG_SPLIT_NO_EMPTY flag for the preg_split function would be useful but because of the bug I didn't use it here.

    you can as well have a counter for all the character sets and see which one of course the most...

    and finally you should consider chopping your string off after 200 chars or something. this should be enough to tell what character set is used.

    and you have to do some error handling! like division by zero, empty string etc etc! don't forget that please... any questions? comment!

    if you want to detect the LANGUAGE of a string, you should split into words and check for the words in some pre-defined tables. you don't need a complete dictionary, just the most common words and it should work fine. tokenization/normalization is a must as well! there are libraries for that anyway and this is not what you asked for :) just wanted to mention it

提交回复
热议问题