Forum Moderators: coopster

Message Too Old, No Replies

Phantom line break!

         

JAB Creations

8:43 am on Aug 26, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This function is designed to take chunks of text from a textarea and stick them in to paragraph elements using nice clean XHTML. However for the life of me I can't figure out how line breaks are appearing before the end tag for the paragraph element on all except the last paragraph in the output.

Any thoughts on what's trying to sink my battleship?

- John

function bb_4_n2p($pizza)
{
$pieces = explode("\n",$pizza);

foreach($pieces as $key => $value)
{
$value=str_replace(" ", " ", $value);
$value=str_replace("\n", "", $value);
$value=str_replace("\r", "", $value);
if (strlen($value)<2) {unset($pieces[$key]);}
}

foreach($pieces as $key => $value)
{
$bb_q = explode("<blockquote>",$value);
$bb_c = explode("<code>",$value);

if (count($bb_c)=='1' && count($bb_q)=='1')
{
$v2 = explode("\n",$value);
if (isset($result)) {$result .= '<p>'.$v2[0]."</p>\n\n";}
else {$result = '<p>'.$v2[0]."</p>\n\n";}
}
else
{
if (isset($result)) {$result .= $value."\n\n";}
else {$result = $value."\n\n";}
}
}
return $result;
}

JAB Creations

5:31 am on Aug 27, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Figured it out.

- John

foreach($pieces as $key => &$value)

coopster

3:29 pm on Aug 28, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Glad you got it sorted. PHP5+ allows for you to modify array values in a foreach [php.net] loop construct by using a reference. One word of advice though, John -- you should get in the habit of destroying that reference after your loop is complete.

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

The example on that page shows you how to destroy the reference.

JAB Creations

12:50 am on Aug 29, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Coopster, I've revised my functions. While I wasn't seeing any trouble I do have a couple related functions with two foreach loops.

- John