I get a string from the frontend which has a line break in it. It is saved in an array which looks like this:
[address] => Array (
[0] => Foo
Bar
)
I then use json_encode() on the array before writing it into the SQL DB:
$string = json_encode( $string, JSON_UNESCAPED_UNICODE );
This turns the array into:
{"address":["Foo\r\nBar"]}
Unfortunately the DB doesn't like \r or \n if not escaped, so it gets rid of the \r and \n.
- So the first question is, is there a function that I can use to properly escape the string, so it can be written properly into the DB without losing the line break?
- I didn't find any function for that, so I tried to use str_replace to just replace the \r\n with \\n. The function is:
$string = str_replace(["\r\n","\r","\n"], "\\n", $string);
This however does not work. I don't know why. The function itself works, as I tried to replace only "n" with "bla" and it worked. However the moment I try to replace the backslash it does not find anything to replace. I don't know if some "special" backslash character is used here or what else could be going on here.
This is driving me nuts, seriously. So I hope somebody can help me out. Thanks in advance.