dongyanjing5975 2013-09-16 23:09
浏览 62
已采纳

打印出Javascript时包含换行符的PHP字符串causins问题

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('
') != -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 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 " " with 'n' in PHP before calling the javascript

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

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

I still doesn't work, output in browser:

<script>
  alert("16 St Andrews Street

Dundee

DD1 2EX");
</script>

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

  • 写回答

4条回答 默认 最新

  • dongyi5570 2013-09-16 23:14
    关注

    Try this:

    $custDetailsEscaped = str_replace("
    ", '
    ', $custDetails);
    

    Note the double quotes for the first argument and single quotes for the second - it's significant here.

    Then replace all instances of $custDetails in your echo statement with $custDetailsEscaped:

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

    Output:

    <script>
      if ('
    123 Main Street
    City
    Area Code
    '.indexOf('
    ') != -1)
         alert('yes');
      alert('
    123 Main Street
    City
    Area Code
    ');
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效