Remove words more then 20 in a string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ajm113
    New Member
    • Jun 2007
    • 161

    Remove words more then 20 in a string?

    Ok, I want to limiter how many words can be displayed from a string, I seen and used this function a while ago where you enter the string and max words you wanted to display.

    Then it would display the max words you wanted it too show.

    I forgot where and how it was made, can anyone help me out?
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    One way would be to simply use the stripos function to count the spaces, and then use substr to print everything until the 20'th space.

    Like:
    [code=php]
    $index = true;
    $count = 0;

    // Loop until 20 words have been found
    // or until no words are left.
    while($count < 20 && $index != false) {
    $index = stripos($input, " ", $index + 1);
    $count++;
    }

    if($index != false) {
    // Print the first 20 words.
    echo substr($input, 0, $index);
    }
    else {
    // String is less than 20 words
    echo $input;
    }
    [/code]
    Last edited by Atli; Aug 8 '08, 02:02 AM. Reason: Fixed the code.

    Comment

    • Ajm113
      New Member
      • Jun 2007
      • 161

      #3
      It could be mine or your code, but it seems that my function doesn't work at all.

      [PHP]function maxWords($input , $max) {
      $index = 0;
      $count = 0;


      while($count < $max && $index != false) {

      $index = stripos($input, " ", $index);
      $count++;

      }



      if($index != false) {

      // Print the first 20 words.

      return substr(0, $index, $input);

      }

      else {

      // String is less than 20 words

      return $input;

      }

      }[/PHP]

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        Ok, did the last post in somewhat of a hurry. Overlooked a few things:

        First, the index variable needs to be initialized to anything except false (or 0). Otherwise the loop will close before it starts.

        Second, the last parameter int he stripos function needs to be one higher then the index, so you need to add a +1 there.

        And lastly, the parameters passed into the substr function are in the wrong order. Should be input, 0, index.

        Think that's all :P

        P.S.
        Fixed the code in my previous post and tested it. It works :P

        Comment

        Working...