我从数据库中得到一个返回字符串。
这个返回字符串必须用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>
<textarea>
,它们应该全部为 \r\n
。无论如何,上述代码只是调整了不同的行尾样式,以便其能够对任何样式产生相同的结果。 - DaveRandom$db = preg_replace("/\n/m", '\n', $db);
这应该能解决问题
^
或 $
时,无需使用 /m
,并且您的表达式应该用单引号表示;-) - DaveRandomm
修饰符 :) 如果主题字符串中没有"\n"字符或模式中没有出现^或$的情况下,设置此修饰符将不起作用。 - Fabrizio Calderan为了正确保留\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);
<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"。
var jdb = "<?php echo $db; ?>"
; - Felix Kling