Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert line breaks to \n

Tags:

javascript

php

I have a return string from a db.

The return string must be formatted in javascript.

<?php
    $db = "this is a line
           this is a new line";
?>

How would I convert the above to:

<?php $db = "this is a line \n this is a new line"; ?>

Javascript:

<script>
    var jdb = <?php echo $db; ?>
</script>
like image 832
dev.bashar Avatar asked Apr 18 '12 12:04

dev.bashar


People also ask

What is the \n in HTML?

The \n character matches newline characters.


2 Answers

Try this (updated 2014-11-08):

<?php

   $db = "this is a line
          this is a new line
          ";

?>
<script type="text/javascript">
  var jdb = <?php echo json_encode($db) ?>;
</script>
like image 61
DaveRandom Avatar answered Sep 29 '22 12:09

DaveRandom


$db = preg_replace("/\n/m", '\n', $db);

should do the trick

like image 42
Fabrizio Calderan Avatar answered Sep 29 '22 12:09

Fabrizio Calderan