Josh Close wrote:

I'm trying to get a simple regex to work. Here is the test script I have.

#!/usr/bin/php -q
<?

$string = "hello\nworld\n";
$string = preg_replace("/[^\r]\n/i","\r\n",$string);

First, the short version. You can fix this by using backreferences:

 $string = preg_replace("/([^\r])\n/i", "\\1\r\n", $string);

Now, the reason:

preg_replace() replaces everything which matched, so both the \n and
the character before it will be replaced (as they both had to match
to make the pattern match).

Luckily, preg_replace() stores a list of matches, which you can use
either later in the same pattern or in the replace string. This is
called a 'backreference'. You can tell preg_replace() which part(s) of
the pattern you want to store in this fashion by enclosing those parts
in parentheses.

In your case, you want to store the character before the \n which matched,
so you would enclose it in parentheses like so: "/([^\r])\n/i". Thereafter
you can refer to that portion of the pattern match with the sequence \1.
If you add another set of parens, you would refer to it with \2...and so
on. You can even nest pattern matches like this, in which case they are
counted by the opening paren. So the replacement string would then become
"\\1\r\n". (You need the extra \ in front of \1 to prevent PHP's string
interpolation parsing the \1 before it gets passed to preg_replace()).

A lot more information is available from the manual page on preg_replace():

  http://www.php.net/preg_replace

There is also an extensive pages on pattern syntax:

  http://www.php.net/manual/en/pcre.pattern.syntax.php


Hope this helps,

Torben

$string = addcslashes($string, "\r\n");

print $string;

?>

This outputs

hell\r\nworl\r\n

so it's removing the char before the \n also.

I just want it to replace a lone \n with \r\n

-Josh

-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to