sign in | join about | help | sitemap
Connecting Tech Pros Worldwide
View Single Post
Justin Koivisto's Avatar
Justin Koivisto July 17th, 2005 11:31 AM
Guest - n/a Posts
#7: Re: php word wrap function needed - one that works

-----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($chars,$str){
~ $cpy=strip_tags($str);
~ $chk=array_reverse(preg_split('`\s`',$cpy));
~ $chk2=array_reverse(preg_split('`\s`',$str));
~ $len=0;
~ $retVal='';

~ // we want to work backwards on this
~ for($i=count($chk)-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($pop1);
~ $pattern='`'.preg_quote($pop1).'`';
~ while(!preg_match($pattern,strip_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 - Join Bytes!
http://www.koivi.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFB2tvhm2SxQ7JEbpoRAoeZAJ9XilXn/AgPBSpdAQe6ihCvpAQKqQCdFVkt
BkTpkYMcJYqJxA8R552govQ=
=IcB0
-----END PGP SIGNATURE-----

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 196,829 network members.
Post your question now . . .
It's fast and it's free