PHP

This php script helps you 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"

?>
in: » Website Programming » PHP | Posted on Sep 14th, 2009 | views 9,309
you can see also:
About the author
i'm moustafa from egypt i love doing one thing 'web programming & designing', This year I've got 19 years old and i'm in the english College of management (in Business Administration part soon)