Invisible line breaks in html via variables (PHP)


#1

Consider the following code:

$Img1 = '<div><img src="images.png"></div>';
$Img2 = '<div><img src="images2.png"></div>';

This is what my HTML looks like when I echo $Img1 and $Img2 together:

<div><img src="images.png"></div><div><img src="images2.png"></div>

This is what I would like it to look like:

<div><img src="images.png"></div>
</div><div><img src="images2.png"></div>

In other words, I would like to have nicely formatted HTML, preferably without inserting breaks…

<br/>

Is there a way to modify $Img1 and #Img2 to accomplish this? I’ve tried /n, /r/n, etc., but I’m either doing something wrong or they only work when echoing the values.

Thanks.


#2

\n, \r\n, and \r all have to be within double quotes, not single quotes.


#3

Were the control characters enclosed with double or single quotes?

Edit:
Ninjaaaad :frowning:


#4

Also forgot to mention that it’s written with a backslash (\) and not a forward slash (/). The order in which they face matters. :slight_smile:


#5

I’m back on the desktop…

Try the following script Using PHP HereDoc Strings:


// BEWARE: ONLY LINEFEED AFTER ____EOT
$imgs = <<< ____EOT
  <div class="w88 mga bgr tac">
    <img 
      src="https://via.placeholder.com/110" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/220" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/320" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/420" 
      width="180" 
      alt="#" 
    />

  </div>
____EOT;
// BEWARE: ONLY LINEFEED AFTER ;

# Maybe CRUNCH  
  if(true):
    $imgs = str_replace(["\n", "\r", "\t", "  "], '', $imgs);
  endif;  

echo $imgs;

#6

I mean, at that point, I’d just go with Twig:

{% spaceless %}
<div class="w88 mga bgr tac">
    <img 
      src="https://via.placeholder.com/110" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/220" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/320" 
      width="180" 
      alt="#" 
    />

    <img 
      src="https://via.placeholder.com/420" 
      width="180" 
      alt="#" 
    />

</div>
{% endspaceless %}

#8

The <br> tag will not put line breaks in your html code, it only puts line breaks in the displayed output in the browser.

Backslash n will do it in doulbe quotes.

$Img1 = "<div><img src="images.png"></div>\n";
$Img2 = "<div><img src="images2.png"></div>\n";

#9

Thanks for all the tips. I don’t know how I got the backslash turned around. I knew there was a difference, and I thought I was doing it right. :wink:

I’ll give the HereDoc string a try, too.