我有一个用PHP编写的代码片段,它从数据库中提取一个文本块,并将其发送到网页上的一个小部件。原文可以是一篇很长的文章,也可以是一两个短句;但是对于这个小部件,我不能显示超过200个字符。我可以使用substr()在200个字符处切断文本,但结果将在单词中间切断——我真正想要的是在200个字符前的最后一个单词的末尾切断文本。


当前回答

好吧,所以我得到了另一个版本的这个基于上面的答案,但考虑到更多的东西(utf-8, \n和 ),如果与wp一起使用,也是剥离wordpress shortcodes注释的行。

function neatest_trim($content, $chars) 
  if (strlen($content) > $chars) 
  {
    $content = str_replace(' ', ' ', $content);
    $content = str_replace("\n", '', $content);
    // use with wordpress    
    //$content = strip_tags(strip_shortcodes(trim($content)));
    $content = strip_tags(trim($content));
    $content = preg_replace('/\s+?(\S+)?$/', '', mb_substr($content, 0, $chars));

    $content = trim($content) . '...';
    return $content;
  }

其他回答

你可以用这个:

function word_shortener($text, $words=10, $sp='...'){

  $all = explode(' ', $text);
  $str = '';
  $count = 1;

  foreach($all as $key){
    $str .= $key . ($count >= $words ? '' : ' ');
    $count++;
    if($count > $words){
      break;
    }
  }

  return $str . (count($all) <= $words ? '' : $sp);

}

例子:

word_shortener("Hello world, this is a text", 3); // Hello world, this...
word_shortener("Hello world, this is a text", 3, ''); // Hello world, this
word_shortener("Hello world, this is a text", 3, '[read more]'); // Hello world, this[read more]

Edit

工作原理:

1. 从输入文本中打开空格:

$all = explode(' ', $text);

例如,如果$text将是"Hello world",那么$all是一个带有爆炸值的数组:

“你好”,“世界”)

2. 对于每个单词:

选择展开文本中的每个元素:

foreach($all as $key){...

将当前单词($key)附加到$str,如果它是最后一个单词,则添加空格:

$str .= $key . ($count >= $words ? '' : ' ');

然后给$count加上1,检查它是否大于max limit($words)打破循环:

if($count > $words){
   break;
}

只有当最终文本小于输入文本时,才返回$str和分隔符($sp):

return $str . (count($all) <= $words ? '' : $sp);

Dave和AmalMurali的代码中添加了IF/ELSEIF语句,用于处理没有空格的字符串

if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) { 
    $WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' ')); 
} 
elseif (strlen($string) > 200) {
    $WidgetText = substr($string, 0, 200);
}
$shorttext = preg_replace('/^([\s\S]{1,200})[\s]+?[\s\S]+/', '$1', $fulltext);

描述:

^ -从字符串开头开始 ([\s\ s]{1200}) -从1到200的任意字符 [\ s] + ?-在短文本结尾不包含空格,这样我们就可以避免使用word…而不是word… [\s\ s]+ -匹配所有其他内容

测试:

让我们加上一些其他的r Regex101.com orrrr正好200个字符。 Regex101.com后第五r orrrrr排除。

享受。

我发现这很有效:

function abbreviate_string_to_whole_word($string, $max_length, $buffer) {
    if (strlen($string) > $max_length) {
        $string_cropped = substr($string, 0, $max_length - $buffer);
        $last_space = strrpos($string_cropped, " ");
        if ($last_space > 0) {
            $string_cropped = substr($string_cropped, 0, $last_space);
        }
        $abbreviated_string = $string_cropped . "&nbsp;...";
    }
    else {
        $abbreviated_string = $string;
    }
    return $abbreviated_string;
}

缓冲区允许您调整返回字符串的长度。

给你:

function neat_trim($str, $n, $delim='…') {
   $len = strlen($str);
   if ($len > $n) {
       preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
       return rtrim($matches[1]) . $delim;
   }
   else {
       return $str;
   }
}