Posted By

ryarwood on 07/08/10


Tagged

php String truncate


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Vordreller


Truncate String


 / Published in: PHP
 

Truncates a string at a certain position without cutting words into senseless pieces.

  1. <?php
  2.  
  3. $string = "Truncates a string at a certain position without cutting words into senseless pieces.";
  4. $maxlength = 75;
  5. $extension = " ...";
  6.  
  7. function truncate_string ($string, $maxlength, $extension) {
  8.  
  9. // Set the replacement for the "string break" in the wordwrap function
  10. $cutmarker = "**cut_here**";
  11.  
  12. // Checking if the given string is longer than $maxlength
  13. if (strlen($string) > $maxlength) {
  14.  
  15. // Using wordwrap() to set the cutmarker
  16. // NOTE: wordwrap (PHP 4 >= 4.0.2, PHP 5)
  17. $string = wordwrap($string, $maxlength, $cutmarker);
  18.  
  19. // Exploding the string at the cutmarker, set by wordwrap()
  20. $string = explode($cutmarker, $string);
  21.  
  22. // Adding $extension to the first value of the array $string, returned by explode()
  23. $string = $string[0] . $extension;
  24. }
  25.  
  26. // returning $string
  27. return $string;
  28.  
  29. }
  30.  
  31. // This Will output:
  32. // "Truncates a string at a certain position without ?cutting? ..."
  33. echo truncate_string ($string, $maxlength, $extension);
  34.  
  35. ?>

Report this snippet  

You need to login to post a comment.