Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \n with '' by using str_replace() in PHP

Tags:

php

I have the following code

$s = '\n [email protected] \n ';
$s = str_replace('\n', '', $s);

echo $s;

I want to replace the '\n' char with '' but it's not working with the above code. I have found that as \n is the new line char with ascii value 10 by echo ord(substr($s, 0, 1)); it is not working. It's not clear to me what is the exact reason behind not working the above code. please help.

like image 973
Devasish Avatar asked Nov 08 '16 12:11

Devasish


2 Answers

You need to place the \n in double quotes. Inside single quotes it is treated as 2 characters '\' followed by 'n'

Try below code:

$s = "\n [email protected] \n";
$s = str_replace("\n", '', $s);

echo $s;
like image 88
Manthan Dave Avatar answered Oct 23 '22 03:10

Manthan Dave


You have to use double quotes. \n is not interpreted as newline with single quotes.

like image 21
Christoph Hösler Avatar answered Oct 23 '22 04:10

Christoph Hösler