Mega Code Archive

 
Categories / Php / Strings
 

Short text sample from long text articles

When you want to show a snippet of text for an article but dont want to cut off words in the middle, use this little function. <?php function shortenText(&$source_text, $word_count) { $word_count++; $long_enough = TRUE; if ((trim($source_text) != "") && ($word_count > 0)) { $split_text = explode(" ", $source_text, $word_count); if (sizeof($split_text) < $word_count) { $long_enough = FALSE; } else { array_pop($split_text); $source_text = implode(" ", $split_text); } } return $long_enough; } // sample use $long_text="a b c d e f g h i j k l m n o p q r s t u v w x y z"; $short_text=$long_text; $more_text_available=shortenText($short_text, 20); echo $short_text; if($more_text_available) { echo '<a href="URL to larger text">more...</a>'; } ?> The text is shortened to the required word length. The returned value tells us if the original text is shorter than the required word length. This can then be used to determine if we want to use a link or script to display the full article.