Here is a function I wrote to cut a string after x chars but it won't cut words... so you always get complete words, even if x is in the middle of a word:
function word_substr($str_String, $int_Length)
{
$str_String = trim($str_String);
$str_String = substr($str_String, 0, $int_Length);
$str_Revstr = strrev($str_String);
$str_LastChar = substr($str_Revstr, 0, 1);
if($str_LastChar == " ") // wurde der String in einem Wort geteilt?
{
//das Leerzeichen am Ende entfernen:
$str_String = substr($str_String, 0, -1);
return $str_String;
}
else
{
$arr_Words = explode(" ", $str_String);
$int_Elements = count($arr_Words);
if($int_Elements == 1)
{
return $arr_Words[0];
}
else
{
array_pop($arr_Words);
$str_String = implode(" ", $arr_Words);
return $str_String;
}
}
}
Here i am writing another function to avoid word breaking at the starting of a string. for example if you are doing db search for a keyword named "love". while displaying client wanted to display 100 character before and 100 character after that word. while we are displaying 100 character before there is a chance for breaking the word at the starting of a sentance, to avoid this we can use the following code:
//Function for checking start position of this sentence is a space or not
function SpaceChecking($content,$startpos)
{
$startpos=$startpos -1;
$data=substr("$content",($startpos),1);
if($data != " ")
{
//Call the same function Recursivly
$startpos=$this->SpaceChecking($content,($startpos-1));
}
return $startpos;
}
PHP Code :- How to avoid Word breaking while we are using substr()
