简体   繁体   English

从字符串中打印固定数量的单词/ tkens

[英]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. 或者,如果有办法让我的查询在$ data4引用的字段中存储有限数量的单词。 In the example below, where I am printing a fixed number of characters $data4 variable I would rather not have any words truncated. 在下面的例子中,我打印固定数量的字符$ data4变量,我宁愿没有任何单词被截断。

<?
$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. 编辑:在最终输出周围添加一个修剪,以摆脱那个讨厌的最后附加空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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