Tutorials Home Scripts Home

Substring without losing word meaning

Substring without losing word meaning

many people some time want to cut specific text to get A small piece of it ,thus this people using substr() function to do that but this function some times give Misunderstandings
so i will give you some codes to do that

firt method

Substring without losing word meaning and tiny words (length 3 by default) are included on the result.


PHP function

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)) ? '...' : '');
}

"..." is added if result do not reach original string length.

this code has the same job of substr() but this code is more effecive becuase its not cut the word.

example

<?php

/**
 * @example one
 */
echo _substr('Hello World My Age Is 19',3);//Returns "Hello..."

?>

second method

this function can cut the words of any text is other mean can helps you limit displaying characters form you text and not cut your word

the function

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

How It Work

  • Define how many characters you want to display.
  • Find what is the last character displaying.
  • If the last character displaying is not " " (space) then go to next character until we found it.
  • Display your message

example

<?php

/**
 * @example one
 */
echo text_limit('Hello World My Age Is 19',3);//this Returns "Hello World My"

?>

Category: Website Programming | Views: 5,513 | on: September 14, 2009 | by: jooria
Enjoyed the article? Subscribe and get the new Tutorials

Enter your email address:

Last 1 Responses

Comment form

  1. dilandinga About 5 months ago
    I bookmarked this link. Thank you for good job!

Leave a Comment

Comment form