This is an Error Message
This is a Success Message
This is an Informative Message

Topics: 15   |   Posts: 14   |   Comments: 12   |   Members: 232

  • 57
  • 0

Limiting Words with PHP

omari Thu May 10, 2012 - 11:29 am

Omari Celestine

If you got extensive content like descriptions and would like just a brief section of that content for example when you you briefly list the articles in blog.

With this function which I've whipped up, you are provided with the choice of using your own separator in which case, your words would not necessarily be separated by spaces.

So whether you have "I love my family more than my friends." or "I-love-my-family-more-than-my-friends.", you can use the this function to strip your words.


<?php
function limit_words($limit,$string,$seperator) {
  $isConsistent = str_replace($seperator,"",$string,$isc);
  if ($isc < 1) {
    echo "Sorry, but your search string does not consist of your seperation string";
  } else {
    $string = explode($seperator,$string);
    if ($limit > count($string)) {
      echo "Your limit is more than the number of words available in your string.";
    } else {
      $i = 0;
      $new_string = "";
      foreach ($string as $word) {
        $i++;
        if ($i <= $limit) {
          $new_string .= $word;
          if ($i < $limit) { $new_string .= $seperator; }
        }
      }

      return $new_string;
    }
  }
}
?>



Now, let's create a brief example using the above function to strip the first four (4) from our sample string above.


<?php
// Define our string or content
$string = "I love my family more than my friends.";
// Set our word limit
$limit = 4;
// Set our separation character
$separator = " ";

// Begin our function
$new_string = limit_words($limit,$string,$separator);
echo $new_string; // I love my family



The above family will use the input string I love my family. and using the space [ ] separator, we would output the first four (4) which would give us: I love my family

As I said before, you are not limited to the space character. I have also built in a basic authentication system for validating the function.

0 ATTACHMENTS

Login or Register to leave a comment.

Topic Search
Get Started