0

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.

Case
  • 4,244
  • 5
  • 35
  • 53
  • Possible duplicate of [How to Truncate a string in PHP to the word closest to a certain number of characters?](http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara) – Brett DeWoody Nov 11 '15 at 19:16
  • Thanks Brett. I am hoping there is a different solution without doing a for loop to count characters. That seems overly simplistic. – Case Nov 11 '15 at 19:35
  • I tested that accepted answer and it will return higher than desired length. – Case Nov 11 '15 at 19:38

1 Answers1

0

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;
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184