HideTran
HideTran

Reputation: 13

PHP - how to print several words in paragraph

In my code, i have:

$row = "Some text in my string";

now i'm using php and print some word in that variable.

for example: i want 2 words: output will be: "Some text"; (etc with 3 words, 4 words)

but i don't know how to do that in php !

Upvotes: 0

Views: 1561

Answers (3)

Kris
Kris

Reputation: 41867

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

Outputs:

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'

Upvotes: 1

Rupesh Pawar
Rupesh Pawar

Reputation: 1917

Try this

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);

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43265

Do it yourself, you will learn some part of PHP

Tips:

  1. Explode the string to get an array of words. function -> explode
  2. take a slice of the array with required number of words. function -> array_slice
  3. join this array slice to get string with required number of words. function -> implode

Upvotes: 0

Related Questions