-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
leegold2 wrote:
| I have been looking for a php word wrap function. I know there's an
| official PHP function but I've tried that and many of the functions
| contributed on that php.net page and none do what I want...and some act
| weird as well.
|
| I want, If I say break at 150 chars then the function will break at the
| nearest space to 150 ie. it will actually break at the word boundry. And
| if theres a url it will not break inside a URL, it will leave URLS alone.
|
| Please state/link me *specifically* what function if you know of one,
| Thanks for the help,
| Lee G.
Here is one that I had thrown together a while back:
function word_wrap($char s,$str){
~ $cpy=strip_tags ($str);
~ $chk=array_reve rse(preg_split( '`\s`',$cpy));
~ $chk2=array_rev erse(preg_split ('`\s`',$str));
~ $len=0;
~ $retVal='';
~ // we want to work backwards on this
~ for($i=count($c hk)-1;$i>=0;$i--){
~ // $len is the current segment length in the stripped string
~ if($len>0 && ($len + strlen($chk[$i])) > $chars){
~ // add a line break
~ $retVal.='<br />'."\n";
~ $len=0;
~ }else if($len>0){
~ // space between words needs to be counted
~ $len++;
~ }
~ // add the necessary pieces to the string
~ $pop1=array_pop ($chk); // get next piece from each version
~ $pop2=array_pop ($chk2);
~ $retVal.=$pop2. ' ';
~ $len+=strlen($p op1);
~ $pattern='`'.pr eg_quote($pop1) .'`';
~ while(!preg_mat ch($pattern,str ip_tags($pop2)) ){
~ // if pop1 and pop2 are not referencing the same element
~ $pop2=array_pop ($chk2);
~ $retVal.=$pop2. ' ';
~ if($pop2==NULL) break;
~ }
~ }
~ return $retVal;
}
It wraps plain text or HTML as it displays (doesn't count the HTML tags
when processing). The string is split on whitespace, if there is a piece
that is longer than the wrap, it outputs just that as it was input.
HTH
- --
Justin Koivisto -
ju****@koivi.co m http://www.koivi.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: Using GnuPG with Mozilla -
http://enigmail.mozdev.org
iD8DBQFB2tvhm2S xQ7JEbpoRAoeZAJ 9XilXn/AgPBSpdAQe6ihCv pAQKqQCdFVkt
BkTpkYMcJYqJxA8 R552govQ=
=IcB0
-----END PGP SIGNATURE-----