Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_php thread: linebreak
every 60 letter


Message #1 by "Florian Heinisch" <florian@h...> on Mon, 7 May 2001 21:44:50
>When I want to display all sent messages via php on the web,
>the message is shown in one row, that means without any linebreaks.
>Can anyone help me?

But first I'm a little surprised that you get it in your browser as
one long string. If you enclose the data in <p> and </p>, the web
browser should format it to fill the visible window no matter how long
the text.

echo ("<p>$oldstring</p>");

should format correctly (and scale itself if the browser size
changes).  If you want a width less than the browser window put it in
a table cell with a defined width.

But since I find string manipulations fun (my version of a crossword
puzzle) here are some thoughts. Personally I wouldn't change the
original string (or even build up a $newstring) but just process and
output in one step with the breaks where you want.

But if you really want to insert <br> at every 60th character, try:

for($i = 0; $i < strlen($oldstring); $i+=60)
  {
    echo (substr ($oldstring,$i,60)."<br>");
  }

The big problem with that little routine is that words spanning the
60th character will be split in the middle. Something more refined is
needed. We end each segment at 60 characters, then work back from
there for find the space, and then advance to the next segment.
Finally we need to output the last segment (otherwise we would have
had a final segment without a space, and the routine would go on for
ever, never outputting the final word!):

$linewidth = 60;
$i = 0;
while ($i < (strlen($oldstring)-$linewidth))
// subtract $linewidth so that the last segment is
// treated specially, otherwise we would get into an
// infinite loop, where the last piece is never output.
  {
     $counter = $linewidth;
     while (substr ($oldstring,$i+$counter, 1) != " ")
     // find the last space
        { $counter--; }
     echo (substr ($oldstring, $i, $counter)."<br>");
     // echo up to the last space
     $i += $counter; // move to the next segment
  }
echo (substr ($oldstring, $i, $linewidth)."<br>");
// we do this to echo last segment which we left out before

Perhaps someone else can do it more efficiently?

I haven't tried this out so there may be (numberous) bugs (usually
missing a ; or two!) and it may not cater for all eventualities... but
it should get one started. You also need to add in some html
formatting (<p> and </p>) and such like.

As I mentioned above this whole process shouldn't be necessary! But I
do use something vaguely similar when making headlines and exerpts for
news items that need to break off after a given number of characters,
but not in the middle of a word.

Regards
Grant

-------------------
Grant Ballard-Tremeer, visit ECO Ltd on the web at
http://ecoharmony.com
HEDON Household Energy Network http://www.ecoharmony.net/hedon/
-------------------



  Return to Index