PHP 将字符串修剪为给定的字数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 将字符串修剪为给定的字数相关的知识,希望对你有一定的参考价值。

<?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 将字符串修剪为给定的字数的主要内容,如果未能解决你的问题,请参考以下文章