PHP Code

PHP: Parse a Substring without Chopping Words

Often times you need cut off a specific string of text to get just a piece of it, perhaps to fit an excerpt of the latest news on your homepage. When you want to do that, you'll need to use the substr() function to do that. The main problem with this though, is that if you create a substring of certain length, you can easily cut words in half and lose their meaning. You need to be able to create a substring that keeps words intact. There are a couple methods that you can use to do this.

The First method is this:

You can create a substring without losing any words. Even the very short, under three letter words (length 3 by default) are going to be included in the result that you get.


function _substr($str, $length, $minword = 3)
{
   $sub = '';
   $len = 0;
   foreach (explode(' ', $str) as $word)
   {
      $part = (($sub != '') ? ' ' : '') . $word;
      $sub .= $part;
      $len += strlen($part);
      if (strlen($word) > $minword && strlen($sub) >= $length)
      {
         break;
      }
   }
   return $sub . (($len < strlen($str)) ? '...' : '');
}
&#91;/code&#93;

If the results dont' add up to the original length, then it will add "..."

So, if you use the following code, it will give you the same end result as substr(), but it can be a lot more effective because it doesn't cut off the word.

&#91;code="langphp""&#93;
<?
  echo _substr('Hello World My Age Is 19',3);//Returns "Hello..."
?>

Second method
This method or function can help you to cut the words off from any text set and it can also help you to limit the display of characters and not cut the words in half.


function text_limit($str,$limit=10)
{
    if(stripos($str," ")){
        $ex_str = explode(" ",$str);
        if(count($ex_str)>$limit) {
            for($i=0; $i < count($ex_str); $i++) {
                $str_s.=$ex_str&#91;$i&#93;." ";
            }
        return $str_s;
        } else {
            return $str;
        }
    } else {
        return $str;
    }

}
&#91;/code&#93;
How It Will Work
1. Simply set the number of characters that you want to show.
2. Decide which is the last character which displays.
 (If the character that is displaying is not " " (space) then you will continue on and go to next character until it is found.)
3. Display the message. Example:

&#91;code="langphp""&#93;
<?
   echo text_limit('Hello World I am 49',3);//this Returns "Hello World I am 49"
?>
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image