I am building a system to create dynamic descriptions for meta tags. It takes the post on the page and feeds it into a function which stripes out everything unnecessary and then takes the strlen see that its to large and creates a list of words. Now, I need to remove the right amount of words to bring the string down to 155 characters or 152 and I will add an ellipsis.
Example String (None of this is actual code its meant for sudo code)
$string = "Hello lovely Solia Avatar Community, I have a little problem and I need your help. I used to have Paint Tool SAI but my laptop ate a lot of my files, one of them being SAI. Now I am trying to get it back but I lost the website I got it from. I keep finding a website to buy it from for about $70.";
echo strlen($string);
= 296
if(strlen($string) > 155) {
// Get word amount
$words = preg_split('/\s+/', ltrim($string), 155 + 1);
}
Now, I have the words in an array and I need to take that array and bring it down to a total strlen of 155 and stop at the nearest word and not break it awkwardly. Maybe I am going about trying to solve this problem incorrectly and I need to be using a different set of functions.
The basic idea is to find the position of the first space after the first 155 characters. This can be done with strpos($string, ' ', 155)
. Then use substr($string, 0, $endat155)
to retrieve the portion of the string from the beginning to that position.
$endat155 = strpos($string, ' ', 155);
$firstWords = substr($string, 0, $endat155);
echo $firstWords;