如何缩短字符串而不切换单词,同时保持PHP中的字符限制

Cam*_*oft 5 php string twitter

可能重复:
如何将PHP中的字符串截断为最接近一定数量字符的单词?

如何在不切换单词的情况下将字符串缩短为最多140个字符.

请使用以下字符串:

$string = "This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this word."

使用substr($string, 0, 140)我们会得到这样的东西:

This is an example string that contains more than 140 characters. If I use PHPs substring function it will split it in the middle of this wo

注意它通过单词"word"切成薄片.

我需要的是能够缩短一个字符串,同时保留整个单词但不超过140个字符.

我确实找到了以下代码,但即使它会保留整个单词,也不能保证整个字符串不超过140个字符限制:

function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

如果字符串太长,您可以先使用substr截断字符串,然后使用正则表达式删除最后一个完整或部分单词:

$s = substr($s, 0, (140 - 3));
$s = preg_replace('/ [^ ]*$/', ' ...', $s);
Run Code Online (Sandbox Code Playgroud)

请注意,您必须使原始文本短于140个字节,因为当您添加...时,这可能会增加字符串的长度超过140个字节.