Jump to content

My array is reversing! why oh why!


php_joe

Recommended Posts

I am trying to write a function that will strip tags and reduce multiple line breaks & tabs to just one. There's probably a better way of doing this, but this is what I've come up with on my own.

 

This strips the tags, breaks each line into an array, separates by tabs, then removes white space.

 

function strip_whitespace($code){
$code = strip_tags($code);
$lines = explode("\n", $code);
foreach($lines as $lkey => $line){
$pieces = explode("\t", $line);
foreach($pieces as $pkey => $piece){
$newpiece[$pkey] = trim($piece);
} // end pieces
$newline[$lkey] = implode("\t", $newpiece);
$newline[$lkey] = trim($newline[$lkey]);
} // end lines
$output = implode("\n", $newline);
return($output);
}

 

However, I still end up with double tabs & double line breaks, so I tried this:

 

function strip_whitespace($code){
$code = strip_tags($code);
$lines = explode("\n", $code);
foreach($lines as $lkey => $line){
$pieces = explode("\t", $line);
foreach($pieces as $pkey => $piece){
$newpiece[$pkey] = trim($piece);
if(!$newpiece[$pkey]) unset($newpiece[$pkey]); // This reverses the array
} // end pieces
$newline[$lkey] = implode("\t", $newpiece);
$newline[$lkey] = trim($newline[$lkey]);
if(!$newline[$lkey]) unset($newline[$lkey]); // but this one works fine
} // end lines
$output = implode("\n", $newline);
return($output);
}

 

Why does the $newpiece array order reverse when I unset() the empty values?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.