The other answers show you how you can make the text roughly 340 characters. If that s fine for you, then use one of the other answers.
But if you want a very strict maximum of 340 characters, the other answers won t work. You need to remember that adding the ...
can increase the length of the string and you need to take account of that.
$max_length = 340;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, , $offset)) . ... ;
}
Note also that here I m using the overload of strrpos
that takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.
See it working online: ideone