Jump to content


Photo

string formatting


  • Please log in to reply
3 replies to this topic

#1 natalieG

natalieG
  • Members
  • PipPipPip
  • Advanced Member
  • 63 posts

Posted 24 June 2006 - 09:31 PM

Does anyone have a small piece of code that wil reformat a
string, by breaking it up into lines of a defined length, separated by
"<BR>" We have a string that can be uo to 300 charc=acters and
want to reformat into eight lines,or so.separated by <BR>.

Jennifer

#2 Orio

Orio
  • Staff Alumni
  • Advanced Member
  • 2,491 posts

Posted 24 June 2006 - 09:36 PM

<?php
$line_len=8; //change value to whatever line length you want
$len=strlen($string);
$lines=ceil($len/$line_len);
$arr=str_split($string, $line_len);
$i=0;
while($i<$lines){
echo($arr[$i]);
echo("<br>");
$i++;
};
?>

This should do it [img src=\"style_emoticons/[#EMO_DIR#]/smile.gif\" style=\"vertical-align:middle\" emoid=\":smile:\" border=\"0\" alt=\"smile.gif\" /]
$string is the string you got.
In this case I chose 8 chars per line.

Orio.
Think you're smarty?

(Gone until 20 to November)

#3 Koobi

Koobi
  • Staff Alumni
  • Advanced Member
  • 419 posts
  • LocationColombo, Sri Lanka | South Asia

Posted 24 June 2006 - 09:37 PM

so you are giving me a string whose length you describe in the number of characters it contains and you want me to break it into lines?

how many characters exist in a line?


i think i might have misunderstood your question.
show me an example of the input you would enter and the output you expect.


in any case, i believe you would find the functions [a href=\"http://www.php.net/substr\" target=\"_blank\"]substr()[/a] and [a href=\"http://www.php.net/strpos\" target=\"_blank\"]strpos()[/a] useful

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 24 June 2006 - 11:03 PM

This will break it naturally at word boundaries


$txt = "Lorem ipsum dolor sit amet. Consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.";

$size = strlen($txt);
$lines = 8;
$linesize = ceil($size/$lines);

echo wordwrap($txt, $linesize,'<BR>');

Gives
Lorem ipsum dolor sit amet.
Consectetuer adipiscing elit, sed
diam nonummy nibh euismod
tincidunt ut laoreet dolore magna
aliquam erat volutpat. Wisi enim
ad minim veniam, quis nostrud
exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea
commodo consequat.

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users