2

I have a PHP string that contains an address and as such contains a few lines. One example could be:

$custDetails = "
123 Main Street
City
Area Code
";

Although this address is retrieved using an SQL query, not declared in PHP.

I would like to replace the go to line characters by something else, temporarily, to make modifying this string easier in another javascript function. But I'm running in to some problems. This code:

echo "
<script>
  if ('$custDetails'.indexOf('\n') != -1)
     alert('yes');
  alert('$custDetails');
</script>
";

Becomes:

<script>
  if ('123 Main Street
City
Area Code'.indexOf('
') != -1)
  alert('yes');
  alert('123 Main Street
City
Area Code');
</script>

after treated by PHP. The "go to lines" in the string are treated as go to line in the script tag, and as such messes up the script. Additionally, I can't detect the \n char because it is treated as a go to line, and messes up the script...

How can I make a string with multiple lines usable in javascript?

EDIT: As suggested in one of the answers, I tried replacing "\n" with 'n' in PHP before calling the javascript

$custDetailsBis = str_replace("\n", '\n', $custDetails);

echo "<script>
alert(\"$custDetailsBis\");
</script>";

I still doesn't work, output in browser:

<script>
  alert("16 St Andrews Street
\nDundee
\nDD1 2EX");
</script>

Note that I know have \n that have appeared on the browser output, but there are still line breaks. Again the line breaks are causing errors in the javascript.

4

4 回答 4

2

尝试这个:

$custDetailsEscaped = str_replace("\n", '\r\n', $custDetails);

注意第一个参数的双引号和第二个参数的单引号 - 这在这里很重要。

$custDetails然后将echo语句中的所有实例替换为$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>
于 2013-09-16T23:14:56.370 回答
1

您可以使用json_encodewhich should 自动将新行替换为\r\n.

json_encode($custDetails);
于 2014-08-05T15:20:00.157 回答
0

在从 php 回显 var 之前,您应该将 \n 替换为 \\n 以便 javascript 将其作为 \n 处理。

于 2013-09-16T23:21:41.070 回答
0

您可以使用 astr_replace()更改End Of Line购买空字符串。

这篇文章可能会有所帮助,@elusive 在他的回答regex中用于替换行尾。

于 2013-09-16T23:19:39.037 回答