Skip to content

Instantly share code, notes, and snippets.

@mghayour
Forked from khal3d/is_rtl.php
Last active May 10, 2021 20:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mghayour/29899988098a5395a33af8763f92eded to your computer and use it in GitHub Desktop.
Save mghayour/29899988098a5395a33af8763f92eded to your computer and use it in GitHub Desktop.
Check if there RTL characters (Arabic, Persian, Hebrew)
<?php
/**
* Is RTL
* Check if there RTL characters (Arabic, Persian, Hebrew)
* this function works in fuzzy mode
*
* @author Khaled Attia <sourcecode@khal3d.com> Mahdi Ghayour <me@mghayour.ir>
* @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)
?>
@atyachin
Copy link

atyachin commented Aug 10, 2018

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_!@#$%^&*?()+-<>"]/';

@arirah
Copy link

arirah commented Jul 23, 2019

@atyachin you missed some special char .. semicolon (;), colon(:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment