我正在编写一个网页,其中涉及使用php数组字符串输出js数组,如下所示
while($main2row = mysqli_fetch_assoc($result)) {
$tSummary[$main2row['id']] = '"'.$main2row['content'].'"';
$tTitle[$main2row['id']] = '"'.$main2row['title'].'"';
}
//the above gets the php from the sql database, then stores it in an array, both are string arrays
foreach ( $tSummary as $key => $val)
{
echo "summArray['".$key."'] = ".nl2br($val).";\n";
}
foreach ( $tTitle as $key => $val)
{
echo "titleArray['".$key."'] = ".nl2br($val).";\n";
}
//these foreach loops will print in a js script and will store the php arrays as js arrays
我知道我应该使用json,但这是其他人为我设置的方式,我觉得我应该遵守他们的代码。
问题在于,当存储数据时,它会以下列方式失败:
summArray['225594172793552897'] = " blah blah blah blah blah - blah.<br />
<br />
blah blah blah blah....."; /* this one is messed up */
summArray['225595300046307328'] = "text text text text text text text text text text text text text text ."; /* this one is fine */
我注意到字符串会在有换行符的地方中断,所以我尝试使用nl2br但是,虽然添加了一个br标签,但它并没有删除换行符。有什么方法可以摆脱这次换行吗?
答案 0 :(得分:0)
而不是nl2br($val)
,请尝试str_replace("\n", "\\n", $val)
获取JavaScript中的换行符,或str_replace("\n", "\\n", nl2br($val))
以获取HTML换行符。