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
Share on other sites

Your code is of error, say there already is an \r\n on the page, You'll be replacing it in order, so \r\n = \r\n = \r\r\n\r\n ...

 

The order of the array is important, so you should use something like Rajivgonsalvas' code.

Link to comment
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.