我正在使用下面的 getExcerpt() 函数来动态设置文本片段的长度。但是,我的 substr 方法目前基于字符数。我想将其转换为字数。我需要单独的函数还是有一个 PHP 方法可以用来代替 substr?
function getExcerpt()
{
//currently this is character count. Need to convert to word count
$my_excerptLength = 100;
$my_postExcerpt = strip_tags(
substr(
'This is the post excerpt hard coded for demo purposes',
0,
$my_excerptLength
)
);
return ": <em>".$my_postExcerpt." [...]</em>";}
}
Run Code Online (Sandbox Code Playgroud)
根据参数,它可以返回字符串中的单词数(默认)或找到的单词数组(以防您只想使用它们的子集)。
因此,要返回一段文本的前 100 个单词:
function getExcerpt($text)
{
$words_in_text = str_word_count($text,1);
$words_to_return = 100;
$result = array_slice($words_in_text,0,$words_to_return);
return '<em>'.implode(" ",$result).'</em>';
}
Run Code Online (Sandbox Code Playgroud)