I would recommend the solution by @jeroen, since it makes use of PHPs native functions to handle JSON.
However, since you've asked, I sense that you do not completely understand why your solution did not work.
As already pointed out in the comments by @B001 you need "\
" for this task:
$trimmed = str_replace("\
", "", $response);
The reason for this is, that "
" represents the new line character when "\
" represents the string "
".
Try the following code and you will see the difference
print("-----");
print("
");
print("-----");
print("\
");
print("-----");
print("\"");
Which will result in the following output:
-----
-----
-----"
The reason for this is that every instance of the "\" character in code, starts a control character. Examples for this are "
" for newline, "" for carriage return, "\t" for tab, \" for the "-character inside a string defined by "" and "\\" for the actual backslash-character.
So if you want to create the actual string containing
, you have to tell the interpreter that you actually want the \-character and not a control character created by \ and what ever character follows. This is done by using double backslashes "\\" which is the string representation of the actual backslash string. This is called "escaping".
In your case you have the actual character string in your $response variable, and you therefore have to use the escaped character as pattern.
Last let me explain the difference between "
" and '
'.
There are two ways in PHP to create a string:
$str1 = "hello
world
";
$str2 = 'hello
world
';
print($str1);
print($str2);
Both variables will contain a string, however, the "-string indicates for the PHP interpreter that the contained string should be interpreted, while the '-string gives you the string as it is. The example above would therefor result in the following output:
hello
world
hello
world
This shows that the following code also would strip your string of the
instances since '
' would contain the actual string and not the control character:
$trimmed = str_replace('
', "", $response);
This interpretation of the "-string goes so far as to allow for variables to be inserted into a string:
$name = "Daniel";
$age = 18;
$sentence = "My Friend $name is $age years old.";
print($sentence);
and would result in:
My Friend Daniel is 18 years old.