0

How to trim unnecessary white space in PHP*

The problem is this. U have 2 if clauses that output string, or an empty string, and I need to put them in a class later on:

<?php
$result1 = ($result_1) ? 'first' : '';
$result2 = ($result_2) ? 'second' : '';

$class_out = trim('clear' . ' ' .$result1. ' ' .$result2);

return '<span class="'.$class_out.'"></span>';
?>

Now, $result_1 and $result_2, can be set, or not, so the possibilities of output should be

<span class="clear first second"></span>
<span class="clear first"></span>
<span class="clear second"></span>
<span class="clear"></span>

But instead they are

<span class="clear first second"></span>
<span class="clear first"></span>
<span class="clear  second"></span><!-- EXTRA SPACE-->
<span class="clear"></span>

Now, this isn't a fault, but it looks kinda ugly. Why have an extra space if it can be avoided? The issue is, how? I found implode function, but that only glues things together, I don't know if it will trim the unnecessary space. What should I use?

dingo_d
  • 11,160
  • 11
  • 73
  • 132

3 Answers3

3

You could use an array instead (resulting in much more readable code in my opinion):

$classes = array('clear');
if ($result_1) {
    $classes[] = 'first';
}
if ($result_2) {
    $classes[] = 'second';
}

$class_out = implode(' ', $classes);
Niko
  • 26,516
  • 9
  • 93
  • 110
2

trim() removes spaces from begining and from end of string you want to replace all multiple spaces with just one.

$class_out = trim('clear' . ' ' .$result1. ' ' .$result2);
$class = preg_replace('!\s+!', ' ', $class_out);
Community
  • 1
  • 1
scx
  • 2,749
  • 2
  • 25
  • 39
1

In your php code, set the spaces in the $result1 and $result2 var

<?php
    $result1 = ($result_1) ? ' first' : '';
    $result2 = ($result_2) ? ' second' : '';

    $class_out = trim('clear' . $result1 . $result2);

    return '<span class="'.$class_out.'"></span>';
?>

And now, no more extra space :)

Niko
  • 26,516
  • 9
  • 93
  • 110
Thelt
  • 81
  • 5