0

在我的代码中,我有:

$row = "Some text in my string";

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

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

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

4

3 回答 3

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);
于 2011-11-01T05:49:04.323 回答
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'
于 2011-11-01T05:53:32.373 回答
0

自己动手,你会学到 PHP 的一部分

提示:

  1. 分解字符串以获得单词数组。功能->explode
  2. 取出具有所需字数的数组切片。功能->array_slice
  3. 加入此数组切片以获取具有所需字数的字符串。功能->implode
于 2011-11-01T05:47:13.047 回答