PHP str_replace not working correctly

偶尔善良 提交于 2020-01-04 05:55:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!