views:

165

answers:

3

Hi, 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?

+3  A: 

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

Ólafur Waage
+5  A: 

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

Brad F Jacobs
`trim()` only removes whitespace characters from the beginning and end of a string, not in the middle.
BoltClock
Yea, it dawned on me he wasn't doing it to the end of the string :) Modified to be a better response!
Brad F Jacobs
A little bit lost now, what's the difference between the two answers?
Omar Abid
Nothing really, mine just shows the code to convert `\r\n` AND `\n` to a ",". I think waage was hinting to this, I just showed the code to accomplish it.
Brad F Jacobs
+2  A: 

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

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