我有一个 PHP 字符串,其中包含一个地址,因此包含几行。一个例子可能是:
$custDetails = "
123 Main Street
City
Area Code
";
尽管该地址是使用 SQL 查询检索的,但未在 PHP 中声明。
我想暂时用其他字符替换转到行字符,以便在另一个 JavaScript 函数中更轻松地修改此字符串。但我遇到了一些问题。这段代码:
echo "
<script>
if ('$custDetails'.indexOf('\n') != -1)
alert('yes');
alert('$custDetails');
</script>
";
变成:
<script>
if ('123 Main Street
City
Area Code'.indexOf('
') != -1)
alert('yes');
alert('123 Main Street
City
Area Code');
</script>
经过PHP处理后。字符串中的“转到行”被视为脚本标记中的转到行,因此会弄乱脚本。此外,我无法检测到\n 字符,因为它被视为跳转行,并且弄乱了脚本......
如何制作可在 JavaScript 中使用的多行字符串?
编辑:正如答案之一所建议的,在调用 javascript 之前,我尝试在 PHP 中将“\n”替换为“n”
$custDetailsBis = str_replace("\n", '\n', $custDetails);
echo "<script>
alert(\"$custDetailsBis\");
</script>";
我还是不行,在浏览器中输出:
<script>
alert("16 St Andrews Street
\nDundee
\nDD1 2EX");
</script>
请注意,我知道浏览器输出中出现了\n,但仍然存在换行符。换行符再次导致 JavaScript 中出现错误。
最佳答案
试试这个:
$custDetailsEscaped = str_replace("\n", '\r\n', $custDetails);
请注意第一个参数的双引号和第二个参数的单引号 - 这在这里很重要。
然后将 echo
语句中 $custDetails
的所有实例替换为 $custDetailsEscaped
:
$custDetailsEscaped = str_replace("\n", '\r\n', $custDetails);
echo "
<script>
if ('$custDetailsEscaped'.indexOf('\\r\\n') != -1)
alert('yes');
alert('$custDetailsEscaped');
</script>
";
输出:
<script>
if ('\r\n123 Main Street\r\nCity\r\nArea Code\r\n'.indexOf('\r\n') != -1)
alert('yes');
alert('\r\n123 Main Street\r\nCity\r\nArea Code\r\n');
</script>
关于javascript - 包含换行符的 PHP 字符串会导致打印 Javascript 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838807/