Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从字符串打印固定数量的单词/tken_Php_Mysql - Fatal编程技术网

Php 从字符串打印固定数量的单词/tken

Php 从字符串打印固定数量的单词/tken,php,mysql,Php,Mysql,基本上,我想知道如何从给定的字符串中打印固定数量的单词。或者,如果有办法让我的查询在$data4引用的字段中存储有限数量的单词。在下面的示例中,当我打印固定数量的字符$data4变量时,我不希望任何单词被截断 <? $sysquery4 = mysql_query("SELECT * FROM content WHERE sid='59' AND title!='' ORDER BY id DESC LIMIT 4") or die(mysql_error()); while($data

基本上,我想知道如何从给定的字符串中打印固定数量的单词。或者,如果有办法让我的查询在$data4引用的字段中存储有限数量的单词。在下面的示例中,当我打印固定数量的字符$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>
<? } ?>

您可以使用以下代码片段(未经测试)解决此问题:

函数限制字($string,$num\u字){
//从字符串中拉出一个单词数组(您可以指定所需的delimeter)
$array\u of_words=分解(“,$string);
//按请求的次数循环数组并生成输出,重新插入空格。

对于($i=1;$i),类似的问题会被问很多次。请检查下面的答案。它们将帮助您解决问题。
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);
}