13

how to remove "\n" in string?
I used 3 method bellow ,seams that only the "\s+" works , but I only want to remove \n,not all space ,how to do the job?
need help, this question had puzzled me for a long time.

$str="<p>
    hello<br>
    world
</p>";

//$str=str_replace("\n","",$str);
$str=preg_replace("@\n@","",$str);
//$str=preg_replace("@\s+@"," ",$str);  
echo $str;
mingfish_004
  • 1,295
  • 2
  • 17
  • 26

2 Answers2

35

This should also do the trick.

$str=str_replace("\r\n","",$str);
Serhiy
  • 2,437
  • 3
  • 33
  • 48
20
$string = trim(preg_replace('/\s\s+/', ' ', $string));

The above code will replace multiple spaces and newlines with a single space.

Gunaseelan
  • 2,323
  • 5
  • 33
  • 40
Hosam Elzagh
  • 1,032
  • 14
  • 25