I have a string that I want to shorten so that it is always 20 characters or less.
- I don't want the words to be cut off.
- When it is too long, I add
(...)
at the end and this(...)
is included in the 20 characters.
$string = "Hello my name is Ana and I live in Egypt";
$length = 20;
if(strlen($string) > $length) {
$string = wordwrap($string, $length - 6); // -6 because we count the chars of " (...)"
$string = explode("\n", $string, 2);
$string = $string[0].' (...)';
}
echo $string; // output "Hello my name (...)"
But now I want to do the exact same thing, but by keeping the last word.
So the expected ouput is : "Hello my (...) Egypt"
I really don't know what's the best approach to do this. If there are any useful functions I don't know about, or maybe Regex?