Question

I'm using str_replace and it's not working correctly. I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".

$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;

Strangely, I receive the following result

Chelsea

,real

,Barcelona

instead of Chealsea,real,Barcelona.

What's wrong?

Was it helpful?

Solution

To expand on Waage's response, you could use an array to replace both sets of characters

$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;

This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n

OTHER TIPS

Try replacing "\r\n" instead of just "\n"

I would trim the text and replace all consecutive CR/LF characters with a comma:

$text = preg_replace('/[\r\n]+/', ',', trim($text))

I had the same issue but found a different answer so thought I would share in case it helps someone.

The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:

str_replace("\\n","<br>",($text))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top