note 36784 deleted from function.substr by aidan

From: Date: Sat, 03 Jul 2004 07:56:53 +0000
Subject: note 36784 deleted from function.substr by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72393@lists.php.net to get a copy of this message
Note Submitter: xeen DOT(lol) dc AT(lol) web DOT(lol) de ---- I read the functions above how to substr a string but don't break in the middle of words. I searched for a function which doesn't break a line or a sentence (breaking by dot would break the following sentence wrong: "The dot "." is balck and small."). So here's my function how to break a string by any string (if that is corret english :D) <? function limitchars($text,$lim,$break,$tail) { $text = split("$break",$text); // If you want this function case insensitive // replace above line with these two lines // $text=preg_replace("/$break/i",strtolower($break),$text); // $text = split(strtolower("$break"),$text); if(strlen(implode("$break",$text))>=$lim) { $i=0; $add_str=""; while($i<=count($text)) { $add_str=$text[$i]; $out[]=$add_str; if(strlen(implode("$break",$out))>=$lim-strlen($break)) break; $add_str=""; $i++; } $text=implode("$break",$out); if(substr($text, 0, -strlen($break))==$break) $text = substr($text, 0, -strlen($break)); $text="$text$tail"; } else { $text=implode("$break",$text); } return $text; } $data="1<br>2<br>3<br>4"; $linebreak="3"; $splitter="<br>"; $tail="..."; echo limitchars($data,$linebreak,$splitter,$tail); // returns: 1... $data="1<br>2<br>3<br>4"; $linebreak="6"; $splitter="<br>"; $tail="..."; echo limitchars($data,$linebreak,$splitter,$tail); // returns: 1<br>2... ?> I hope this function helps and has enough features to substr a text correctly.

« previous php.notes (#72393) next »