我正在使用php函数返回单词而不是字符当我将字符串传递给函数但我有一个变量等于包含字符串的另一个变量并且我尝试了主变量但是没有工作
////////////////////////////////////////////////////////
function words($text)
{
$words_in_text = str_word_count($text,1);
$words_to_return = 2;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}
$intro = $blockRow03['News_Intro'];
echo words($intro);
/* echo words($blockRow03['News_Intro']); didn't work either */
结果是什么
答案 0 :(得分:1)
str_word_count无法正确处理重音(多字节)字符。你可以使用sanitize words
函数来解决这个问题:
function sanitize_words($string) {
preg_match_all("/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u",$string,$matches,PREG_PATTERN_ORDER);
return $matches[0];
}
function words($text)
{
$words_in_text = sanitize_words($text);
$words_to_return = 2;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}
$intro = "aşağı yukarı böyle birşey";
echo words($intro);