php - str_word_count() 函数不能正确显示阿拉伯语

标签 php function

我已经创建了下一个函数来从文本中返回特定数量的单词:

function brief_text($text, $num_words = 50) {
    $words = str_word_count($text, 1);
    $required_words = array_slice($words, 0, $num_words);
    return implode(" ", $required_words);
}

它在英语语言中运行良好,但当我尝试在阿拉伯语中使用它时,它失败了,并且没有按预期返回单词。例如:

$text_en = "Cairo is the capital of Egypt and Paris is the capital of France";
echo brief_text($text_en, 10);

将输出开罗是埃及的首都,巴黎是

$text_ar = "القاهرة هى عاصمة مصر وباريس هى عاصمة فرنسا";
echo brief_text($text_ar, 10); 

将输出�� �� �� �� �� �� ��

我知道问题出在 str_word_count 函数上,但我不知道如何解决。

更新

我已经编写了另一个函数,它在英语和阿拉伯语中都运行良好,但我正在寻找一个解决方案,以解决在使用阿拉伯语时 str_word_count() 函数引起的问题。无论如何,这是我的另一个功能:

    function brief_text($string, $number_of_required_words = 50) {
        $string = trim(preg_replace('/\s+/', ' ', $string));
        $words = explode(" ", $string);
        $required_words = array_slice($words, 0, $number_of_required_words); // get sepecific number of elements from the array
        return implode(" ", $required_words);
    }

最佳答案

试试这个函数来统计字数:

// You can call the function as you like
if (!function_exists('mb_str_word_count'))
{
    function mb_str_word_count($string, $format = 0, $charlist = '[]') {
        mb_internal_encoding( 'UTF-8');
        mb_regex_encoding( 'UTF-8');

        $words = mb_split('[^\x{0600}-\x{06FF}]', $string);
        switch ($format) {
            case 0:
                return count($words);
                break;
            case 1:
            case 2:
                return $words;
                break;
            default:
                return $words;
                break;
        }
    };
}



echo mb_str_word_count("القاهرة هى عاصمة مصر وباريس هى عاصمة فرنسا") . PHP_EOL;

资源

建议

  • 使用标签<meta charset="UTF-8"/>在 HTML 文件中
  • 始终添加 Content-type: text/html; charset=utf-8服务页面时的标题

关于php - str_word_count() 函数不能正确显示阿拉伯语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13884178/

相关文章:

php - MySQL php - 添加三个数据并排序

jquery - DataTables row.add() 函数不会添加数组中的所有行

javascript - 映射并返回已解决的 promise 数组的函数的名称?

mysql - 我在 R 中编写了一个查询(SQL)来从数据库中获取一些数据。我想传递由 R 中的子例程指定的日期,而不是对其进行硬编码

python - 如何更有效地求平方和?

php - 如何从 WooCommerce 获取所有结帐字段?

javascript - 用另一个 HTML 替换 HTML 标签

php - 如果可能的话,我将如何从 ajax 调用中设置一个 php 数组?

php - 没有正则表达式的句子大小写

arrays - C中偶数数组的递归