Skip to content

Instantly share code, notes, and snippets.

@vinacode
Created March 31, 2015 08:20
Show Gist options
  • Save vinacode/f07ea45ce572f5e41825 to your computer and use it in GitHub Desktop.
Save vinacode/f07ea45ce572f5e41825 to your computer and use it in GitHub Desktop.
Check Japanese Characters string
<?php
class JapaneseCharacters {
/**
* Check character is half-width Katakana
*
* @param string $char
* @return boolean
*/
public static function checkKatakana($char) {
return (preg_match('/[\x{FF61}-\x{FF9F}]/u', $char) > 0);
}
/**
* Count lent string utf8 full=1, half=0.5
* @param string $str
* @return float
*/
public static function strlen_utf8($str = '') {
if ($str === "") {
return 0;
}
$count = 0;
$str = str_replace('&#34;', '"', $str);
$str = str_replace('&#39;', "'", $str);
$str = str_replace("\r", '', $str);
$str = html_entity_decode($str);
$w_list = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
for ($i = 0; $i < count($w_list); $i++) {
if ((strlen($w_list[$i]) > 1 || ($w_list[$i] == "\n")) && !self::checkKatakana($w_list[$i])) {
$count += 1;
} else {
$count += 0.5;
}
}
return $count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment