0

I want to add a backslash "\" before all non alphanumeric characters like "how are you \:\)", so I used this:

$code = preg_replace('/([^A-Za-z0-9])/i', '\$1', $code);

But it doesn't work. Instead it just echos '\$1'. What am I doing wrong?

I also tried

$code = preg_replace('/([^A-Za-z0-9])/i', '\\$1', $code);

But won't work.

2
  • 1
    You missed one \ (as it needs to be escaped, it should be \\$1)
    – kero
    Aug 20, 2014 at 11:02
  • I tried \\ too but no use. Aug 20, 2014 at 11:03

2 Answers 2

4

You need four backslashes:

 $code = preg_replace('/([^A-Za-z0-9])/i', '\\\\$1', $code);

The reason is that the backslash escapes itself in PHP string context (even single quotes). For PCRE to see even one, you need at least two. But to not being misinterpreted to mask the replacement placeholder, you need to double that still. (Btw, three backslashes would also accidentially work.)

1
  • 2
    echo preg_replace('~([^A-Za-z0-9 ])~', '\\\\$1', $mystring); if you don't want to add \ before spaces. Aug 20, 2014 at 11:07
-1

EXAMPLE:

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.