PHP - 如何在段落中打印几个单词

时间:2011-11-01 05:45:26

标签: php string echo words

在我的代码中,我有:

$row = "Some text in my string";

现在我正在使用php并在该变量中打印一些单词。

例如:我想要2个单词:输出将是:“Some text”; (等等3个字,4个字)

但我不知道如何在php中做到这一点!

3 个答案:

答案 0 :(得分:1)

试试这个

function limit_words($string, $word_limit)
    {
        $words = str_word_count($string, 1);
        return implode(" ",array_splice($words,0,$word_limit));
    }


    $content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    echo limit_words($content,20);

答案 1 :(得分:1)

<?php

function firstNWords($inputText, $number)
{
    // using a regular expression to split the inputText by anything that is considered whitespace
    $words = preg_split('~\s~', $inputText, -1, PREG_SPLIT_NO_EMPTY);
    // make sure the number of words we want will not be out of range
    $number = min(count($words), $number);  
    // slice the number of words we want from the array and glue them together with spaces
    return implode(' ', array_slice($words, 0, $number));
}

// loop over the numbers 1..10 and print print some output for test purposes
for ($i = 1; $i < 10; $i ++)
{
    printf("%d: '%s'\n", $i, firstNWords('The Quick brown fox jumps over the lazy dog', $i));
}

输出:

1: 'The'
2: 'The Quick'
3: 'The Quick brown'
4: 'The Quick brown fox'
5: 'The Quick brown fox jumps'
6: 'The Quick brown fox jumps over'
7: 'The Quick brown fox jumps over the'
8: 'The Quick brown fox jumps over the lazy'
9: 'The Quick brown fox jumps over the lazy dog'

答案 2 :(得分:0)

自己动手,你将学习PHP的某些部分

提示:

  1. 分解字符串以获取单词数组。功能 - &gt; explode
  2. 用一定数量的单词取一个数组。功能 - &gt; array_slice
  3. 连接此数组切片以获取具有所需字数的字符串。功能 - &gt; implode