سؤال

i'm using a php function to return words instead of characters it works fine when i pass string to the function but i have a variable equals another variable containing the string and i've tried the main variable but didn't work

////////////////////////////////////////////////////////
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 */

the result is nothing

هل كانت مفيدة؟

المحلول

str_word_count won't work correctly with accented (multi-byte) characters. you can use below sanitize words function to overcome this problem:

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); 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top