Trim a string without cutting words in PHP

Often we require to trim/cut a string to desired length. Using a function is suggested as writing code again and would be tedious task.

Below is the code of function by which we can cut a string to a desired length without cutting a word (optional) and including a desired symbol at the end of trimmed string.

[php]
function limitlength($oldstring, $newlength, $symbol, $method, $mode)
{
if($symbol==’0′)
{
$symbol="";
}
elseif($symbol==’1′)
{
$symbol="..";
}

$oldstring_len=strlen($oldstring);
if($oldstring_len>$newlength)
{

if($method==’1′)
{
preg_match(‘/(.{‘ . $newlength . ‘}.*?)b/’, $oldstring, $matches);
$newstring=rtrim($matches[1]);
}
else
{
$newstring=substr($oldstring,0,$newlength);
}
$newstring.=$symbol;
}
else
{
$newstring=$oldstring;
}

if($mode==’0′)
{
return($newstring);
}
elseif($mode==’1′)
{
echo "$newstring";
}
}
$newstring=limitlength("I am writing here some long string. But this string is not very long.", 25, "..", 0,0);
echo $newstring;
[/php]

In the code above, there is a function limitlength to which we pass various settings like string to be trimmed, maximum length, if any symbol is to be used at the end of new string, trim string to desired length or trim string to without cutting of any word and mode to return or print result.

Leave a Comment