title: How to truncate a string in PHP to the sentence closest to a certain number of characters?
body: <p>I want to truncate/shorten my string to the sentence closest to a ceratain number of characters.</p>
  
  <p>I have a working function, but my function truncate to the word closest to a certaion number of characters instead.</p>
  
  <pre><code>function shortenString($string, $your_desired_width) {
    $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
    $parts_count = count($parts);
  
    $length = 0;
    $last_part = 0;
    for (; $last_part &lt; $parts_count; ++$last_part) {
      $length += strlen($parts[$last_part]);
      if ($length &gt; $your_desired_width) { break; }
    }
  
    return implode(array_slice($parts, 0, $last_part));
  }
  </code></pre>
  
  <p>For example:</p>
  
  <blockquote>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
    malesuada eleifend orci, eget dignissim ligula porttitor cursus.
    Praesent in blandit enim. Maecenas vitae eleifend est. Cum sociis
    natoque penatibus et magnis dis parturient montes, nascetur ridiculus
    mus. Maecenas pulvinar gravida tempor.</p>
  </blockquote>
  
  <p>Should be shortened to:</p>
  
  <blockquote>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
    malesuada eleifend orci, eget dignissim ligula porttitor cursus.</p>
  </blockquote>
  
  <p>Instead of breaking the sentence like this:</p>
  
  <blockquote>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
    malesuada eleifend orci, eget dignissim ligula porttitor cursus.
    <strong>Praesent in</strong></p>
  </blockquote>
  
  <p>Help is appreciated.</p>