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) Commented Aug 20, 2014 at 11:02
  • I tried \\ too but no use. Commented 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.)

Sign up to request clarification or add additional context in comments.

1 Comment

echo preg_replace('~([^A-Za-z0-9 ])~', '\\\\$1', $mystring); if you don't want to add \ before spaces.
-1

EXAMPLE:

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

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.