Reputation: 237
I have a string that I want to shorten so that it is always 20 characters or less.
(...)
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?
Upvotes: 0
Views: 281
Reputation: 237
So here's how I did it. It doesn't handle cases where the first and last words are more than 20 characters long, but that's what I'm looking for because the priority is that the words are not cut.
function shorten($string, $length = 20) {
if(strlen($string) > $length) {
$words = explode(' ', $string);
$lastWord = end($words);
$charsLastWord = strlen($lastWord);
$string = wordwrap($string, $length - 7 - $charsLastWord); // -7 because we count the chars of " (...) "
$string = explode("\n", $string, 2);
$string = $string[0].' (...) '.$lastWord;
}
return $string;
}
echo shorten("Hello my name is Ana and I live in Egypt");
// output Hello my (...) Egypt
echo shorten("Hello my name is Ana and I live in ACountryWithALongName");
// output Hello (...) ACountryWithALongName
Upvotes: 1