2014-01-13 38 views
2

这是我在我的Word模板功能修剪我需要更换我的话修剪成字符修剪

<?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 .= '&hellip;'; 
    } 
} 
return $string; 
} 

?> 

,并在页面本身,它看起来像这样

<?php echo word_trim(get_the_excerpt(), 12, ''); ?> 

我想知道,有没有一种方法可以修改该功能来修剪字符数量而不是字数?因为有时当有更长的单词时,它们全部被抵消和未对齐。

谢谢

+0

您是否尝试过使用['substr()'](http://php.net/substr)?例如。 'substr($ string,0,$ count)'。这基本上不是你想要做的? –

回答

1

看看功能的逻辑: 它分割一个空间,计数和结果数组切片的字符串,并将它们放在一起回来。
现在空格是单词的分隔符......我们需要分割字符串以获取所有字符而不是单词?没错(更好地说:空字符串)!

使您无论这些线路

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不接受空定界符(根据manual)。

我会将函数重命名为character_trim或其他东西,也许$word变量也是如此,所以您的代码对读者来说是有意义的。