简体   繁体   中英

print a fixed number of words/tkens from a string

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>
<? } ?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM