Revision: 45326
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at April 28, 2011 15:57 by finalwebsites
Initial Code
<?php function substr_words($str, $txt_len, $end_txt = '...') { $words = explode(' ', $str); $count = 0; $new_str = ''; $abbr = ''; foreach ($words as $val) { if ($count < $txt_len) { $new_str .= $val.' '; $count = $count + strlen($val); } } $new_str = rtrim($new_str, ' ,.;:'); if (strlen($str) > $txt_len) $new_str .= $end_txt; return $new_str; } $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.'; echo substr_words($str, 100, '...'); /* Will output: Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce... */
Initial URL
http://www.finalwebsites.com/portal
Initial Description
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.
Initial Title
Sub-string function based on words
Initial Tags
Initial Language
PHP