Limit text to a certain number of chars, but stop when a period is found within the final 20 chars <p>So, I have this function to produce an excerpt from large texts.</p> <pre class="lang-php prettyprint-override"><code>function excerpt( $string, $max_chars = 160, $more = '...' ) { if ( strlen( $string ) &gt; $max_chars ) { $cut = substr( $string, 0, $max_chars ); $string = substr( $cut, 0, strrpos( $cut, ' ' ) ) . $more; } return $string; } </code></pre> <p>This works just fine for it's intends - it limits a given text to a certain number of chars, without cutting words. </p> <p><strong>Here's a working example</strong>:</p> <pre class="lang-php prettyprint-override"><code>$str = "The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours."; echo excerpt( $str, 160 ); </code></pre> <p><strong>This produces this output</strong>:</p> <blockquote> <p>The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid...</p> </blockquote> <p>However, I'm trying to figure out <strong>how to stop if a period, an exclamation or an interrogation mark is found</strong> within the excerpts last 20 chars. So, using the above sentence, it would produce this output:</p> <blockquote> <p>The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer.</p> </blockquote> <p>Any ideas how to archive this?</p>