Jump to content

str_replace Help!


stuckwithcode

Recommended Posts

I am trying to make sure that all line breaks in a piece of text are converted to \r\n.  When I use the code below for:

 

a

b

c

 

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

 

 

After using mysql_real_escape_string the output shows:

 

a\r\r\n\r\nb\r\r\n\r\nc

 

Where am I going wrong? I expected it to remain at a\r\nb\r\nc

 

If I use $text = str_replace(array("\r\n","\r","\n"), "\r", $text); , it works.

 

 

Link to comment
https://forums.phpfreaks.com/topic/187233-str_replace-help/
Share on other sites

oni-kun Thanks for the reply but I didn't quite understand your explanation of how I got

 

a\r\r\n\r\nb\r\r\n\r\nc

 

and could someone explain how

 

$text = preg_replace('#[\r\n]+#', "\r\n", $text);

 

works.

 

You're using an array in your str_replace function. What the array does, is essentially iterates through each one and replaces it.

(\r, \n, \r\n)

 

\r \n and \r\n will be replaced. So if on the page there is '\n', it'll become '\r\n'. Then what?  There's more elements in the array you have. the '\r' in '\r\n' will become '\r\n\r', and again, '\r\r\n\r'. The array makes you replace the replacement's replacement in other words, you're overwriting your result.

Link to comment
https://forums.phpfreaks.com/topic/187233-str_replace-help/#findComment-988758
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.