问题
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?
回答1:
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
回答2:
Try replacing "\r\n"
instead of just "\n"
回答3:
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
回答4:
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))
来源:https://stackoverflow.com/questions/3654844/php-str-replace-not-working-correctly