Reputation: 15976
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?
Upvotes: 2
Views: 5759
Reputation: 31
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))
Upvotes: 3
Reputation: 48284
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
Upvotes: 4
Reputation: 18853
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
Upvotes: 8