Sub-string function based on words


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

I need often for dynamic websites a text snippet with an extact text length. Using the PHP function substr() is a solution, but makes the last word unreadable. This tiny function takes care about the max. string length characters, keeps the last word intact and will add a custom string to the end. This string can be some dots or maybe the link to the whole text.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function substr_words($str, $txt_len, $end_txt = '...') {
  4. $words = explode(' ', $str);
  5. $count = 0;
  6. $new_str = '';
  7. $abbr = '';
  8. foreach ($words as $val) {
  9. if ($count < $txt_len) {
  10. $new_str .= $val.' ';
  11. $count = $count + strlen($val);
  12. }
  13. }
  14. $new_str = rtrim($new_str, ' ,.;:');
  15. if (strlen($str) > $txt_len) $new_str .= $end_txt;
  16. return $new_str;
  17. }
  18.  
  19. $str = 'Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce scelerisque orci ac elit laoreet semper. Vivamus interdum sodales pharetra. Nulla purus lectus, suscipit at consectetur a, egestas et est. Nulla id varius arcu. Ut ac tellus vel diam sodales consequat. Nunc at odio adipiscing dui pellentesque pharetra eu ut tortor. Mauris non imperdiet purus. Etiam ut arcu et justo egestas ornare eu quis risus. Suspendisse potenti. Vivamus eget eros at diam volutpat vehicula eget ac mi.';
  20.  
  21. echo substr_words($str, 100, '...');
  22. /*
  23. Will output:
  24. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce...
  25. */

URL: http://www.finalwebsites.com/portal

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.