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


当前回答

我发现这很有效:

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 . " ...";
    }
    else {
        $abbreviated_string = $string;
    }
    return $abbreviated_string;
}

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

其他回答

虽然这是一个相当老的问题,但我想我可以提供一个替代方案,因为它没有被提到,而且对PHP 4.3+有效。

您可以使用sprintf系列函数来截断文本,方法是使用%。ℕs精密修改器。

句号。后面跟着一个整数,它的含义取决于 说明符: 对于e, e, f和f说明符:这是小数点后要打印的位数(默认情况下,这是6)。 对于g和g说明符:这是要打印的有效数字的最大数量。 对于说明符:它作为一个截断点,设置字符串的最大字符限制

简单截断https://3v4l.org/QJDJU

$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var_dump(sprintf('%.10s', $string));

结果

string(10) "0123456789"

扩展截断https://3v4l.org/FCD21

因为sprintf的功能类似于substr,并且会部分切断单词。下面的方法将通过使用strpos(wordwrap(…, '[break]'), '[break]'),并使用特殊的分隔符。这允许我们检索位置,并确保我们不匹配标准的句子结构。

返回不部分截断单词且不超过指定宽度的字符串,同时保留换行符(如果需要)。

function truncate($string, $width, $on = '[break]') {
    if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {
        $string = sprintf('%.'. $p . 's', $string);
    }
    return $string;
}
var_dump(truncate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 20));

var_dump(truncate("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 20));

var_dump(truncate("Lorem Ipsum\nis simply dummy text of the printing and typesetting industry.", 20));

结果

/* 
string(36) "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
string(14) "Lorem Ipsum is" 
string(14) "Lorem Ipsum
is" 
*/

使用wordwrap($string, $width)或strtok(wordwrap($string, $width), "\n")的结果

/*
string(14) "Lorem Ipsum is"
string(11) "Lorem Ipsum"
*/

基于@Justin Poliey的正则表达式:

// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
if(strlen($very_long_text) > 120) {
  $matches = array();
  preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
  $trimmed_text = $matches[0]. '...';
}

你可以用这个:

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);

Keep in mind whenever you're splitting by "word" anywhere that some languages such as Chinese and Japanese do not use a space character to split words. Also, a malicious user could simply enter text without any spaces, or using some Unicode look-alike to the standard space character, in which case any solution you use may end up displaying the entire text anyway. A way around this may be to check the string length after splitting it on spaces as normal, then, if the string is still above an abnormal limit - maybe 225 characters in this case - going ahead and splitting it dumbly at that limit.

当涉及到非ascii字符时,还有一个类似的警告;包含它们的字符串可能会被PHP的标准strlen()解释为比实际更长,因为单个字符可能占用两个或更多字节,而不是一个字节。如果你只是使用strlen()/substr()函数来分割字符串,你可能会在字符中间分割字符串!如果有疑问,mb_strlen()/mb_substr()更简单一些。

/*
Cut the string without breaking any words, UTF-8 aware 
* param string $str The text string to split
* param integer $start The start position, defaults to 0
* param integer $words The number of words to extract, defaults to 15
*/
function wordCutString($str, $start = 0, $words = 15 ) {
    $arr = preg_split("/[\s]+/",  $str, $words+1);
    $arr = array_slice($arr, $start, $words);
    return join(' ', $arr);
}

用法:

$input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';
echo wordCutString($input, 0, 10); 

这将输出前10个单词。

preg_split函数用于将字符串拆分为子字符串。要分割字符串的边界是使用正则表达式模式指定的。

Preg_split函数需要4个参数,但目前只有前3个与我们相关。

第一个参数-模式 第一个参数是要拆分字符串的正则表达式模式。在本例中,我们希望跨单词边界分割字符串。因此,我们使用预定义的字符类\s来匹配空格字符,如空格、制表符、回车和换行。

第二个参数-输入字符串 第二个参数是我们要分割的长文本字符串。

第三个参数-限制 第三个参数指定应该返回的子字符串的数量。如果将限制设置为n,则preg_split将返回一个包含n个元素的数组。前n-1个元素将包含子字符串。最后(第n个)元素将包含字符串的其余部分。