PHP Get First Characters of String in Complete Sentences

/ Published in: PHP
Save to your folder(s)

Pass in text and the maximum allowable length and this snippet will return as many full sentences from the text as it can within that length. If no sentences, it will just trim to the maximum length allowed.

Copy this code and paste it in your HTML
  1. function trim_text_in_sentences($intLength, $strText) {
  2. $intLastPeriodPos = strpos(strrev(substr($strText, 0, $intLength)), '.');
  3. if ($intLastPeriodPos === false) {
  4. $strReturn = substr($strText, 0, $intLength);
  5. } else {
  6. $strReturn = substr($strText, 0, ($intLength - $intLastPeriodPos));
  7. }
  8. return $strReturn;
  9. }


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.