Search code examples
javascriptphpvariablestrim

Remove line breaks from a js file when writing it with php


So my javascript file is BLANK. I write into it using php. I take the lines from my datafile and use them inside the text.

This is the PHP:

<?php
$myFile = "datafile.txt";
$lines = file($myFile);
$line0 = $lines[0]; //Linija 1
$line1 = $lines[1]; //Linija 2
$line2 = $lines[2]; //Linija 3
$line3 = $lines[3]; //Linija 4
$line4 = $lines[4]; //Linija 5
$line5 = $lines[5]; //Linija 6
$line6 = $lines[6]; //Linija 7

$empty = "\n\n";
$hex = 'var '.$line4.' = "<button class="provjeri" onclick="'.$line1.'()">PROVJERI</button> <button class="rijesi" onclick="'.$line2.'()">RIJEŠI</button>";';


$fp = fopen("js/rijesenja.js", "a");
fwrite($fp, $hex);
fwrite($fp, $empty);
fclose($fp);

This is the datafile.txt:

1
geo1
a1
isprava1
gumbi1
alfa1
ponovi1

I need the output to look like this:

var gumbi1= "<button class="provjeri" onclick="geo1()">PROVJERI</button> 
<button class="rijesi" onclick="a1()">RIJEŠI</button>";

Actually everything should fit in one line.

And the output i get is:

var gumbi1
 = "<button class="provjeri" onclick="geo1
()">PROVJERI</button> <button class="rijesi" onclick="a1
()">RIJEŠI</button>";

It seems to be that ater every variable it breaks the line. I have tried:

var_dump(preg_match('/^\n|\n$/', $variable));

And I also tried:

preg_replace( "/\r|\n/", "", $yourString );

I also tried the trim() command but without any success. Any suggestions on what I should try next?


Solution

  • Because I was using File() to get the file in an array it automatically puts the newline (aka \n) after the variable and when it's written into a new file it skips to the next line. A way to get around this:

    $lines = file($myFile, FILE_IGNORE_NEW_LINES);
    

    The FILE_IGNORE_NEW_LINES attribute omits newline at the end of each array element. And therefore you won't have the code go into the next line but rather it will all stay on the same line.