Invisible line breaks in html via variables (PHP)

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.

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

2 Likes

Were the control characters enclosed with double or single quotes?

Edit:
Ninjaaaad :frowning:

1 Like

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:

1 Like

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;

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 %}
2 Likes

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";

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.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.