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

Viewed 23891

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

10 Answers

this will check if the string is Arabic Or has Arabic text

text must be UNICODE e.g UTF-8

$str = "بسم الله";
if (preg_match('/[اأإء-ي]/ui', $str)) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

Use regular expression for shorter and easy answer

 $is_arabic = preg_match('/\p{Arabic}/u', $text);

This will return true (1) for arabic string and 0 for non arabic string

I would use regular expressions to get the number of Arabic characters and compare it to the total length of the string. If the text is for instance at least 60% Arabic charactes, I would consider it as mainly Arabic and apply RTL formatting.

/**
 * Is the given text mainly Arabic language? 
 *
 * @param string $text string to be tested if it is arabic. :-)
 * @return bool 
 */
function ct_is_arabic_text($text) {
    $text = preg_replace('/[ 0-9\(\)\.\,\-\:\n\r_]/', '', $text); // Remove spaces, numbers, punctuation.
    $total_count = mb_strlen($text); // Length of text
    if ($total_count==0)
        return false;
    $arabic_count = preg_match_all("/[اأإء-ي]/ui", $text, $matches); // Number of Arabic characters
    if(($arabic_count/$total_count) > 0.6) { // >60% Arabic chars, its probably Arabic languages
        return true;
    }
    return false;
}

For inline RTL formatting, use CSS. Example class:

.embed-rtl {
 direction: rtl;
 unicode-bidi: normal;
 text-align: right;
}
public static function isArabic($string){
    if(preg_match('/\p{Arabic}/u', $string))
        return true;
    return false;
}
Related