note 36784 modified in function.substr by vincent

From: Date: Wed, 22 Oct 2003 12:01:41 +0000
Subject: note 36784 modified in function.substr by vincent
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-59115@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 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. --was-- 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. http://www.php.net/manual/en/function.substr.php

« previous php.notes (#59115) next »