我有一个包含地址的PHP字符串,因此包含几行。一个例子可能是:
$custDetails = "
123 Main Street
City
Area Code
";
尽管此地址是使用 SQL 查询检索的,而不是在 PHP 中声明的。
我想暂时用其他字符替换 go to 行字符,以便在另一个 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治疗后。字符串中的"转到行"在脚本标记中被视为转到行,因此会弄乱脚本。此外,我无法检测到 ' 字符,因为它被视为转到行,并且弄乱了脚本...
如何使具有多行的字符串在 javascript 中可用?
编辑:正如其中一个答案所建议的,在调用javascript之前,我尝试在PHP中将"'"替换为"n"
$custDetailsBis = str_replace("'n", ''n', $custDetails);
echo "<script>
alert('"$custDetailsBis'");
</script>";
我仍然不起作用,在浏览器中输出:
<script>
alert("16 St Andrews Street
'nDundee
'nDD1 2EX");
</script>
请注意,我知道浏览器输出中出现了',但仍然有换行符。换行符再次导致 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>
您可以使用json_encode
它应该自动用'r'n
替换新行。
json_encode($custDetails);
您可以使用
str_replace()
来更改购买空字符串End Of Line
。
这篇文章可能会有所帮助,@elusive在他的回答中使用regex
来替换行尾。
在从 php 回显 var 之前,您应该将 ' 替换为 ''',以便 javascript 将其处理为 '。