简体   繁体   English

如何将换行符转换为\\ n

[英]How do I convert line breaks to \n

I have a return string from a db. 我有一个db的返回字符串。

The return string must be formatted in javascript. 返回字符串必须以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: 使用Javascript:

<script>
    var jdb = <?php echo $db; ?>
</script>

Try this (updated 2014-11-08): 试试这个(更新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>
$db = preg_replace("/\n/m", '\n', $db);

应该做的伎俩

要正确保留\\r\\n换行符,您可以轻松使用strtr

$db = strtr( $db, array(  "\n" => "\\n",  "\r" => "\\r"  ));

我不明白这一点,但你可以(通过添加反斜杠来逃避换行)

$db = str_replace("\n","\\n",$db);
$db = str_replace("\r\n", "\\n", $db);

I am not sure if I understand correctly because \\n is a line break!? 我不确定我是否理解正确,因为\\ n是换行符!?

But you may be need: 但您可能需要:

$db = str_replace("\r\n", "\n", $db);

You want to output that to javascript... hmm, so if you want to insert it into html you probably want something like this (the test ran): 你想将它输出到javascript ...嗯,所以如果你想将它插入到html中,你可能想要这样的东西(测试运行):

<div id="test"></div>
<script type="text/javascript">
<?php
  $string = "123
  456"; // or $string = "123\n456";
  $string = str_replace(array("\r\n","\n"),"\\\\n",$string);
  echo "document.getElementById('test').innerHTML = '".htmlentities($string)."';";
?>
</script>

with output 123\\n 456 to the div through the js 通过js输出123\\n 456到div

If you simply want it as that in js, just remove two of the slashes so it's "\\n" in php and "\\n" in js. 如果您只是想在js中使用它,只需删除两个斜杠,使其在php中为“\\ n”,在js中为“\\ n”。

You should look at nl2br(), which converts all new lines to HTML <br />. 您应该查看nl2br(),它将所有新行转换为HTML <br />。 http://php.net/manual/en/function.nl2br.php http://php.net/manual/en/function.nl2br.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM