Trimming A String After # of Occurances of space chars.

Discussion in 'PHP' started by 2blind2c#, Feb 21, 2008.

  1. #1
    Well I figure that I want to trim a string after say, 100 or 200 words (want to ensure that feeds I'm bringing in to post for aggregator are just excerpts and not entire posts).

    So now I'm figuring I may as well go about this by counting space characters " "and after say... 100 space characters I'd like to trim & return this string from the function that'll be trimming (right after 100th occurance of space character of course). So uhh... once again any help on this would be greatly appreciated :D :D :D
     
    2blind2c#, Feb 21, 2008 IP
  2. stoli

    stoli Peon

    Messages:
    69
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Here is one way of doing it:
    <?php
    
    $text = "Pack my box with five dozen liquor jugs";
    $maxwords = 6;
    
    for ($i=0,$words=0;$i<strlen($text);$i++) {
      if ($text[$i] == " ") $words++;
      if ($words == $maxwords) break;
      $newtext .= $text[$i];
    }
    
    echo $newtext;
    
    ?>
    PHP:
    Just set your $text and $maxwords as appropriate, $newtext will contain the truncated string.
     
    stoli, Feb 21, 2008 IP
    2blind2c# likes this.
  3. 2blind2c#

    2blind2c# Peon

    Messages:
    147
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    BWAHAHAHAHA!!!! I was spending hours figuring out why the "new string" was looping continuously & nothing was trimmed, only to realize that I wasn't matching my current variables to what you had was for the old string & new string :D

    THANKS stoli !!! :D :D :D
     
    2blind2c#, Feb 21, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    This is a little more forgiving than counting spaces.
    $str[0] will contain the string.
    <?php
    $text = 'this is a sentence, that has some words -- for testing with -- and stuff, ja know? chicken bo ?';
    $words = 9;
    
    preg_match('#^[^a-z]*([a-z-]+[^a-z-]+){1,'.$words.'}#', $text, $str);
    
    var_dump($str);
    ?>
    PHP:
     
    joebert, Feb 21, 2008 IP