Search code examples
phpforeachexplodeline-breaks

php explode foreach strange line breaks


I got a textarea filled with color codes like 000000 & ffffff each color is on a seperate line so it looks like:

000000
111111
222222

Now I am converting these to actual inline background colors with this:

$bgclass = $params->get('bgclass');
$bgcolors = $params->get('bgcolors');

$bglines = explode("\n", $bgcolors);
if ( !empty($bglines) ) {
  echo "<style>";
  foreach ( $bglines as $bgline ) {
    echo "." . $bgclass . "-" . $bgline . "{background:#" . $bgline . ";}" . "\r\n";
  }
  echo "</style>";
}

This is now outputting like this:

<style>
.bg-000000
{background:#000000
;}
.bg-111111
{background:#111111
;}
.bg-222222
{background:#222222
;}
</style>

How can I get the output to go like this:

<style>
.bg-000000{background:#000000;}
.bg-111111{background:#111111;}
.bg-222222{background:#222222;}
</style>

Solution

  • Just explode() on \r\n instead:

    $bglines = explode("\r\n", $bgcolors);
    

    Another option would be to trim() it:

    $bglines = explode("\n", $bgcolors);
    $bglines = array_map('trim', $bglines);
    

    If this were a file (as I originally thought) then I would use file() to read the file into an array and strip the line endings:

    $bglines = file('/path/to/file.txt', FILE_IGNORE_NEW_LINES);