Reputation: 85
Basically I want to know how I can print a fixed number of words from a given string. Or, if there is a way to have my query store a limited number of words in the field referenced by $data4. In the example below, where I am printing a fixed number of characters $data4 variable I would rather not have any words truncated.
<?
$sysquery4 = mysql_query("SELECT * FROM content WHERE sid='59' AND title!='' ORDER BY id DESC LIMIT 4") or die(mysql_error());
while($data4 = mysql_fetch_array($sysquery4)) {
$year = substr($data4['date'], 0, 4);
$month = substr($data4['date'], 5, 2);
$day = substr($data4['date'], 8, 2);
?>
<div class="post">
<h2>
<? echo $data4['title']; ?>
</h2>
<span class="news_date"><? echo date('F j, Y', mktime(0,0,0,$month,$day,$year)); ></span><br />
<? echo substr($data4['content'], 0,180) ;echo $lnk="... more"; ?>
</div>
<? } ?>
Upvotes: 0
Views: 1099
Reputation: 1209
You could solve this with the following snippet (untested):
function limitWords($string, $num_words){
//Pull an array of words out from the string (you can specify what delimeter you'd like)
$array_of_words = explode(" ", $string);
//Loop the array the requested number of times and build an output, re-inserting spaces.
for ($i = 1; $i <= $num_words; $i++) {
$output .= $array_of_words[$i] . " ";
}
return trim($output);
}
EDIT: added a trim around the final output to get rid of that pesky last appended space.
Upvotes: 2