str_word_count and Arabic text

半城伤御伤魂 提交于 2021-02-11 06:20:44

问题


I used the function str_word_count to count how many ARABIC words are in a text, but it returns zero:

$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';

Thanks in advance


回答1:


Try to use this function

if (!function_exists('utf8_str_word_count')){
     function utf8_str_word_count($string, $format = 0, $charlist = null) {
            if ($charlist === null) {
                $regex = '/\\pL[\\pL\\p{Mn}\'-]*/u';
            }
            else {
                $split = array_map('preg_quote',
                preg_split('//u',$charlist,-1,PREG_SPLIT_NO_EMPTY));
                $regex = sprintf('/(\\pL|%1$s)([\\pL\\p{Mn}\'-]|%1$s)*/u',
                implode('|', $split));
            }
            switch ($format) {
                default:
                case 0:
                    // For PHP >= 5.4.0 this is fine:
                    return preg_match_all($regex, $string);
        
                    // For PHP < 5.4 it's necessary to do this:
                    // $results = null;
                    // return preg_match_all($regex, $string, $results);
                case 1:
                    $results = null;
                    preg_match_all($regex, $string, $results);
                    return $results[0];
                case 2:
                    $results = null;
                    preg_match_all($regex, $string, $results, PREG_OFFSET_CAPTURE);
                    return empty($results[0])
                            ? array()
                            : array_combine(
                                array_map('end', $results[0]),
                                array_map('reset', $results[0]));
            }
         }
       }

Example

$sentence = 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ';
$countSentence = utf8_str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';


来源:https://stackoverflow.com/questions/25631654/str-word-count-and-arabic-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!