| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [1998-06-26 20:49 UTC] philip at qs dot co dot nz
 The ereg_replace command does not correctly substitute
backslash escaped strings correctly.
In the following example:
  $s1="One\nTwo\n\nEnd\nWhere have the nnns gone";
  $s2 = ereg_replace("\n","\\n",$s1);
  $s3 = ereg_replace("\\n","\n",$s2);
Produces for $s2
"One\nTwo\n\nEnd\nWhere have the nnns gone"
But Produces for $s3:
"O
e\
Two\
\
E
d\
Where have the 
s go
e
"
The command appears to be replacing the \\ with \\ and the n with linefeed
Looking at the lengths of the strings string s3 is the same length as string s2.
This behaviour is not affected by the setting of magic_quotes_runtime.
The behaviour is the same for both inbuilt or system regex library.
The DOS version 3.0b6 also has this behaviour.
The workaround is to use stripslashes for unix. Stripslashes does not
work as expected under the DOS version (3.0b6).
Background:
There is a problem with the mysql odbc driver under linux which 
replaces all linefeeds in text fields with spaces. To avoid this it
is necessary to escape all line feeds before inserting into the 
tables.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 04:00:01 2025 UTC | 
Looks like expected behaviour to me. When you put an escape sequence inside a quoted string in PHP it gets replaced by its corresponding value before getting sent to the function you are using it in. That means you have to double-escape escape sequences for regex functions for which escape sequences also have meaning. A bit confusing, but the only real way to stay consistent. So, if you want to escape all newlines simply do this: $s2 = ereg_replace("\n","\\\n",$s1); That looks for a newline and replaces it with a backslash (which you of course have to escape) followed by a newline. So, \\ to represent the backslash and \n to represent the newline.