-
-
Save mghayour/29899988098a5395a33af8763f92eded to your computer and use it in GitHub Desktop.
Check if there RTL characters (Arabic, Persian, Hebrew)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Is RTL | |
* Check if there RTL characters (Arabic, Persian, Hebrew) | |
* this function works in fuzzy mode | |
* | |
* @author Khaled Attia <[email protected]> Mahdi Ghayour <[email protected]> | |
* @param String $string | |
* @return float betwwen 0~1, (0 for ltr and 1 for rtl) | |
* @example if( is_rtl($string) > 0.5 ) { // do sth } | |
*/ | |
function is_rtl( $string ) { | |
$rtl_chars_pattern = '/[\x{0590}-\x{05ff}\x{0600}-\x{06ff}]/u'; | |
preg_match_all($rtl_chars_pattern, $string, $matches); | |
$rtl_chars_count = count($matches[0]); | |
$ltr_chars_pattern = '/[a-zA-Z]/'; | |
preg_match_all($ltr_chars_pattern, $string, $matches); | |
$ltr_chars_count = count($matches[0]); | |
return $rtl_chars_count==0? 0: | |
$ltr_chars_count==0? 1: | |
$rtl_chars_count/($ltr_chars_count+$rtl_chars_count); | |
} | |
// Arabic Or Persian | |
var_dump(is_rtl('نص عربي أو فارسي')); // 1 | |
// Hebrew | |
var_dump(is_rtl('חופש למען פלסטין')); // 1 | |
// Latin | |
var_dump(is_rtl('Hello, World!')); // 0 | |
// both | |
var_dump(is_rtl('سلام من فارسی بیشتری دارم hello')); // 0.8 (There is 80% chance of RTL string) | |
var_dump(is_rtl('سلام helo')); // 0.5 (both have same RTL and LTR characters, There is 50% chance of RTL string) | |
var_dump(is_rtl('سلام hello, i have more ltr')); // 0.19 (There is 19% chance of RTL string) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note that you have division by zero if a number is passed as $string. Try passing '12345' for example.
You easily fix by changing line 17 to:
$ltr_chars_pattern = '/[a-zA-Z0-9_!@#$%^&*?()+-<>"]/';