我已经创建了下一个函数来从文本中返回特定数量的单词:
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;
资源
- Unicode list for arabic
- A Rule-Based Arabic Stemming Algorithm
- A Rule and Template Based Stemming Algorithm for Arabic Language (似乎更完整)
建议
- 使用标签
<meta charset="UTF-8"/>
在 HTML 文件中 - 始终添加
Content-type: text/html; charset=utf-8
服务页面时的标题
关于php - str_word_count() 函数不能正确显示阿拉伯语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13884178/