If you just count the words the resulting sting could still be very long as a single "word" might have 30 characters or more. I would suggest instead truncating the text to 100 characters, except if this causes a word to be truncated then you should also remove the truncated part of the word. This is covered by this related question:
How to Truncate a string in PHP to the word closest to a certain number of characters?
Using wordwrap
$your_desired_width = 100;
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, 100);
$i = strpos($string, "
");
if ($i) {
$string = substr($string, 0, $i);
}
}
This is a modified versions of the answer here. if the input text could be very long you can add this line before the call to wordwrap to avoid wordwrap having to parse the entire text:
$string = substr($string, 0, 101);
Using a regular expression (Source)
$string = preg_replace('/s+?(S+)?$/', '', substr($string, 0, 100));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…