NEWS- display first 50 words, how?

2 posts by 2 authors in: Forums > CMS Builder
Last Post: October 25, 2010   (RSS)

Re: [mrmzalewski] NEWS- display first 50 words, how?

Pretty easy mrmzalewski,

Here's a recipe from my CMSB Cookbook http://www.thecmsbcookbook.com that describes exactly how to do what you're looking for:

Insert this function at the top of your page, or before you want to invoke the word limiting function:

<?PHP
function maxWords($textOrHtml, $maxWords) {
$text = strip_tags($textOrHtml);
$words = preg_split("/\s+/", $text, $maxWords+1);
if (count($words) > $maxWords) { unset($words[$maxWords]); }
$output = join(' ', $words);

return $output;
}
?>


Then put this code where you want the words limited (to 50 words):

<?PHP echo maxWords($record['content'], 50);
?>
If you want to add ...more and a link, use something like this:

<?PHP echo maxWords($record['content'], 50);
?>...<a href="<?php echo $record['_link']; ?>”>Read More</a>

or

<?PHP echo maxWords($record['content'], 5);
?>...<a class="read-more" href="http://www.your_site.com/your_detail_page.php?<?php echo $record['num'] ?>">(Read More)</a>


To allow certain tags like or <p> to appear in your text, change the strip_tags code:

$text = strip_tags($textOrHtml);
to

$text = strip_tags($textOrHtml, '<br />');

The function is pretty literal, but it seems to automatically include the closing tag, so include all the flavors of all the tags (spaces
and slashes, slashes with no space, etc.) that you want to include. Like this:

$text = strip_tags($textOrHtml, '<br /><p>');

If you’re using a WYSIWYG Editor and are losing some formatting when using the MaxWord function, Jason Sauchuk of Interactive Tools
suggests using this version of the function instead:

<?PHP
function maxWords($textOrHtml, $maxWords) {
$text=str_replace("<p>","*P*",$textOrHtml);
$text= str_replace("</p>","*/P*",$text);
$text = strip_tags($text);
$words = preg_split("/\s+/", $text, $maxWords+1);
if (count($words) > $maxWords) { unset($words[$maxWords]); }
$output = join(' ', $words);
$output=str_replace("*P*","<p>",$output);
$output=str_replace("*/P*","</p>",$output);
$output.="</p>";

return $output;
}
?>


Hope that gets you where you want to go,

Best,

Jerry Kornbluth
Head Chef
The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php