str_replace无法通过输入唤醒

问题描述 投票:1回答:2

为了删除新行,以下代码运行良好;

<?php 
  $text = "Hello \nwelcome to \ngeeksforgeeks"; 
  $text = str_replace("\n", "", $text); 
 echo $text; 
?>

输出:您好,欢迎来到geeksforgeeks。

但是当我得到它作为输入时,它不起作用;

 <form method="post">
       <label>enter string</label>&nbsp
       <input type="text" name="string"></input><br><br>
       <input type="submit" name="enter"></input>
 </form>
<?php 
    if(isset($_POST['enter']))
    {
      $text=$_POST['string'];
     $out=str_replace("\n","",$text);
      echo $out;

     }
 ?>

INPUT:您好,\ n欢迎来到\ ngeeksforgeeks;

输出:您好\欢迎来到\ ngeeksforgeeks。

请告诉我原因

php string
2个回答
3
投票

在双引号字符串中,\n是转义序列,成为换行符。您要在用户输入中匹配文字\n,因此应使用单引号字符串,该字符串不处理转义序列。

if(isset($_POST['enter']))
{
    $text=$_POST['string'];
    $out=str_replace('\n',"",$text);
    echo $out;
}

请参见What is the difference between single-quoted and double-quoted strings in PHP?


0
投票

$ out = str_replace('\ n',“”,$ text);要么$ out = str_replace(“ \\ n”,“”,$ text);

© www.soinside.com 2019 - 2024. All rights reserved.