【问题标题】:I need to replace my word trim into characters trim我需要将我的单词 trim 替换为字符 trim
【发布时间】:2014-02-01 05:09:34
【问题描述】:

这是我在模板中用于单词修剪的功能

<?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, ''); ?>

我想知道,有没有一种方法可以修改该函数来修剪字符数而不是单词数?因为有时当有更长的单词时,它会全部偏移并且不对齐。

谢谢

【问题讨论】:

  • 您是否尝试过使用substr()?例如。 substr($string, 0, $count)。这不是你想要做的吗?

标签: php regex function trim texttrimming


【解决方案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 变量,因此您的代码对读者来说是有意义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多