这是我在模板中用于单词修剪的功能
<?php
/**
* Trim a string to a given number of words
*
* @param $string
* the original string
* @param $count
* the word count
* @param $ellipsis
* TRUE to add "..."
* or use a string to define other character
* @param $node
* provide the node and we'll set the $node->
*
* @return
* trimmed string with ellipsis added if it was truncated
*/
function word_trim($string, $count, $ellipsis = FALSE){
$words = explode(' ', $string);
if (count($words) > $count){
array_splice($words, $count);
$string = implode(' ', $words);
if (is_string($ellipsis)){
$string .= $ellipsis;
}
elseif ($ellipsis){
$string .= '…';
}
}
return $string;
}
?>
在页面本身中,它看起来像这样
<?php echo word_trim(get_the_excerpt(), 12, ''); ?>
我想知道,有没有办法修改该功能来修剪字符数而不是单词数? 因为有时当有较长的单词时,它都会偏移和未对齐。
谢谢
看看函数的逻辑:它按空格拆分字符串,对生成的数组进行计数和切片,然后将它们重新组合在一起。
现在空格是单词的分隔符...我们需要在什么字符上拆分字符串以获取所有字符而不是单词?对,什么都没有(最好说:一个空字符串)!
所以你改变了这两行
function word_trim($string, $count, $ellipsis = FALSE){
$words = explode(' ', $string);
if (count($words) > $count){
//...
$string = implode(' ', $words);
}
//...
}
自
$words = str_split($string);
//...
$string = implode('', $words);
你应该没事。
请注意,我将第一个explode
-call 更改为 str_split
,因为explode
不接受空分隔符(根据手册)。
我会将函数重命名为 character_trim
或其他名称,也许还会重命名 $word
变量,这样您的代码对读者来说就有意义了。