Show first x number of words or a comment....

Discussion in 'PHP' started by mnymkr, Feb 21, 2007.

  1. #1
    I hope I asked that correctly.

    On my site... www.shareyourexpertise.com I have a comment tab (on main page) . In the back there is a paramater to to show the number of letters to display of the comment (it is a db field).

    Is there a php command I can use to I can tell it to show I certain number of words not letters?
     
    mnymkr, Feb 21, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Something like this?
    
    <?php
    
    function fetch_words($text, $words = 10)
    {
    	$chunk = array_chunk(preg_split('/\s+/', $text), $words);
    	return implode(' ', $chunk[0]);
    }
    
    $text = 'this is a stupid text blah blah blah';
    
    echo fetch_words($text, 5);
    
    ?>
    
    PHP:
     
    nico_swd, Feb 21, 2007 IP
  3. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #3
    but how would i pull it from the database and make it display only a certian number of words.....sorry i am new to this......

    so say the database filed contained


    "Harry met Sally on the road to Melbourne"

    and I wanted to display only 3 words or how many I choose....thanks1
     
    mnymkr, Feb 21, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Pull the whole text from the database and use the function on variable.

    I can't post the exact code you need cause I haven't seen your's. But it's something like this.

    
    
    $text = 'Harry met Sally on the road to Melbourne';
    
    echo fetch_words($text, 5);
    
    PHP:
    With 5 being the number of words you want to display.
     
    nico_swd, Feb 23, 2007 IP