any ways to get the first 50 words??

Discussion in 'PHP' started by LOD, Sep 9, 2009.

  1. #1
    hi guys
    i want to extract the first 50 word from a text.. is there any php function which will let me do that??
    thanks in advance..
     
    LOD, Sep 9, 2009 IP
  2. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #2
    I think this regex will do the trick
    
      $numwords = 50;
      preg_match("/(\S+\s+){0,$numwords}/", $long_string, $regs);
      $short_string = trim($regs[0]);
    
    PHP:
     
    superdav42, Sep 9, 2009 IP
  3. hamidof

    hamidof Peon

    Messages:
    619
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try this:

    
    preg_match('#((?:\S+\s+){50})#', $string, $matches);
    echo $matches[1];
    
    PHP:
    This is similar to the above but the actual index in the array is 1 not 0. Also you the above regex will match the first word only...
     
    hamidof, Sep 10, 2009 IP
  4. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Why do we need regex, won't

    
    $text = substr($text, 0, 50);
    
    PHP:
    Do the trick?? Where $text is the text you want to trim to 50 characters. You can save it in a new variable, that one just overwrites $text.
     
    wd_2k6, Sep 10, 2009 IP
  5. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #5
    That would work if you want to get the first 50 Characters but he was asking for the first 50 words. In which case it's best to use a regex that counts the first 50 words. See http://www.the-art-of-web.com/php/truncate/ for more methods of truncating text.
     
    Last edited: Sep 10, 2009
    superdav42, Sep 10, 2009 IP
  6. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #6
    ooooooops I see I see
     
    wd_2k6, Sep 10, 2009 IP
  7. LOD

    LOD Member

    Messages:
    319
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    35
    #7
    dude. read the question properly.. i said 50 words not characters..
    but thanks anyways..
     
    LOD, Sep 10, 2009 IP
  8. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Yeah I said oops I had realised the mistake already, so why point it out again?
    Thanks anyways...
     
    wd_2k6, Sep 10, 2009 IP
  9. LOD

    LOD Member

    Messages:
    319
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    35
    #9
    can anyone explain the patter part of the preg_match??
     
    LOD, Sep 10, 2009 IP