将字符串显示为最多这么多字符而不分割单词

Boa*_*rdy 2 php substring

我目前正在开发一个php项目,我需要显示一个最多100个字符的字符串,但不会分割单词.

例如,如果我有字符串

快速的棕色狐狸跳过懒狗

假设第100个角色处于'跳跃'的中间.目前我正在使用substr($mystring, 0, 100)

然后打印出来

快速的棕色狐狸jum

相反,在这种情况下,我想要打印

快速的棕色狐狸

这有可能解决吗?

web*_*ave 5

$string = 'The quick brown fox jumped over the lazy dogs back';
$maxLength = 20;

if (strlen($string) > $maxLength) {
    $stringCut = substr($string, 0, $maxLength);
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')); 
}

echo $string;

// output: The quick brown fox
Run Code Online (Sandbox Code Playgroud)

关键是使用strrpos来切断空格而不是单词的中间位置.

注意:如果这些字符串的源使用多字节字符集,例如UTF-8,则需要使用多字节等效函数.