这个问题已经在这里有了答案:
11年前关闭。
如何在不切分单词的情况下将字符串缩短到最多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);
}
最佳答案
如果字符串太长,则可以首先使用substr截断字符串,然后使用正则表达式删除最后一个完整或部分单词:
$s = substr($s, 0, (140 - 3));
$s = preg_replace('/ [^ ]*$/', ' ...', $s);
请注意,您必须使原始文件短于140字节,因为添加...可能会使字符串的长度增加到140字节以上。