3

I want to replace \n with \\n, and \a with \\a and so on...

So this is my regex:

Pattern:

([\\])

Should be replaced with:

$1$1

So if the input string is \n, it will be replace with \n. (I have tested it at http://www.regexe.com/ and it worked)

Then I had this PHP code:

preg_replace('/([\\])/', '$1$1', "\n a");

and thought it would output \n a, but instead I got this error:

Warning:  preg_replace(): Compilation failed: missing terminating ] for character class at offset 5

So I have escaped the [.

Now my code is

  preg_replace('/(\[\\])/','$1$1',"\n a");

But.... this doesn't works as I want, because now it is not replacing \n with \\n.

What am I doing wrong?

Jop Holp
  • 53
  • 5
  • 1
    `[\\]` is a wrong escaping, you need 4 backslashes to represent one literal ``\``. I'd just suggest using a regular `str_replace` with arrays for search and replace with mapped whitespace and their literal representations. – Wiktor Stribiżew Feb 19 '16 at 22:07
  • 1
    You also need to change `"\n a"` to `'\n a'`. Escape sequences are interpreted inside double quotes so `\n` is a newline, not a backslash followed by `n`. – Barmar Feb 19 '16 at 22:13
  • Have you got any testing framework for this? Do you just target [these PHP escape sequences](http://php.net/manual/en/regexp.reference.escape.php)? – Wiktor Stribiżew Feb 19 '16 at 22:22
  • 1
    As Barmar answered, `preg_replace` is not needed. Further why use a capture group? [`preg_replace('/\\\/', '\\\\\\', '\n a');`](https://eval.in/522094). – bobble bubble Feb 19 '16 at 22:38
  • Unless you give more context, there is no real solution. `How to escape \n` - by just saying _`escape`_ you've put it into the realm of string parsing, which is a lot more complicated than you think. –  Feb 20 '16 at 00:09

2 Answers2

2

You don't need to use preg_replace, you can use str_replace, since you're not matching a pattern. And you need to put the subject string in single quotes, otherwise \n will be treated as the escape sequence for newline.

str_replace('\\', '\\\\', '\n a');

See What is the difference between single-quoted and double-quoted strings in PHP?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Take another delimiter and add a backslash:

<?php
echo preg_replace('~([\\\])~', '$1$1', '\n a');
// output: \\n a
?>
Jan
  • 42,290
  • 8
  • 54
  • 79