note 36784 added to function.substr

From: Date: Wed, 22 Oct 2003 10:38:35 +0000
Subject: note 36784 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-59111@lists.php.net to get a copy of this message
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(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. ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+36784 Delete -- http://master.php.net/manage/user-notes.php?action=delete+36784&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+36784&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#59111) next »