so i have this string where its too long to be put in my report. my report should use only 36 char. but my string value is more than that :
$value = "The quick brown fox jumps over the lazy dog" //43 character
if only get the 36 char so you'll get : "The quick brown fox jumps over the l" but i want to divide the sentence by words not by character, so i want to make 2 variable from that
$var1 = "The quick brown fox jumps over the" //instead of The quick brown fox jumps over the l
$var2 = "lazy dog"
how do i do it???
You need to use wordwrap() here. Try this:
echo substr($value, 0, strpos(wordwrap($value, 36), "
"));
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('The quick brown fox jumps over the lazy dog', 5);
This code will work on any given string, addding word by word and checking every time for limits.
$var1=""; $var2="";
$value="your string";
while ($var1.strlen<36) {
$n=strpos($value, " "); //length of first word
if (($var1.strlen +$n)<36) {
$var1=$var1+substr($value, 0, $n);//from beginning of value till the first 'space' char
$value = substr($value, $n); //removing first word
}
}
$var2=$value;//the remmaining is what is left for second row
This might help you. Result will be array containing string chunk
$value = "The quick brown fox jumps over the lazy dog";
$arr = explode(" ",$value);
$str_arr = array();
$str = $arr[0];
$char_limit = 36;
foreach($arr as $key=>$value)
{
$tmp_str = isset($arr[$key + 1])?$arr[$key + 1]:"";
if(strlen($str." ".$tmp_str) <= $char_limit)
{
$str.=" ".$tmp_str;
}
else
{
$str_arr[]=$str;
$str=$tmp_str;
}
}
$str_arr[]=$str;
print_r ($str_arr);