我有一个来自数据库的返回字符串。
返回字符串必须采用 javascript 格式。
<?php
$db = "this is a line
this is a new line";
?>
我将如何将上述转换为:
<?php $db = "this is a line \n this is a new line"; ?>
Javascript:
<script>
var jdb = <?php echo $db; ?>
</script>
我有一个来自数据库的返回字符串。
返回字符串必须采用 javascript 格式。
<?php
$db = "this is a line
this is a new line";
?>
我将如何将上述转换为:
<?php $db = "this is a line \n this is a new line"; ?>
Javascript:
<script>
var jdb = <?php echo $db; ?>
</script>
试试这个(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);
我不确定我是否理解正确,因为 \n 是换行符!?
但您可能需要:
$db = str_replace("\r\n", "\n", $db);
你想将它输出到 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>
通过js输出123\n 456到div
如果你只是想在 js 中使用它,只需删除两个斜杠,使其在 php 中为“\n”,在 js 中为“\n”。
您应该查看 nl2br(),它将所有新行转换为 HTML <br />。 http://php.net/manual/en/function.nl2br.php