0

I have this string

d = "&&hell+lo";

I want to prepand \ before all special characters. SO the expected output i want is

\&&hell\+o

Here i am doing in two regex but not giving the expected output:

rex1 = d.replace(/[+-=&&><!(){}[\]"~*?:\/]/g, "\\$&");
alert(rex1);
rex2 = d.replace(/&{2}/g, "\\$&");
alert(rex2);

I checked this link but could not find how to replace && in the given string.

I want to run this in both javascript and PHP also.

text.replace(/[+-=><!(){}[\]"~*?:\/]|&&/g, "\\$&") work fine in JS but if i do

$pattern = "/[+-=><!(){}[\]\"~*?:\/]|&&/"; 
echo preg_quote("he+l&&lo", $pattern);

in PHP, its not working

Community
  • 1
  • 1
Manish Kumar
  • 9,298
  • 16
  • 72
  • 128
  • You have put `&&` in a character class. `&&` is not a character. It needs to be outside the character class like in this demo: https://regex101.com/r/pT6dC7/1 – Stephan Nov 20 '15 at 13:17
  • 1
    yes it worked. `|&&` was a trick – Manish Kumar Nov 20 '15 at 13:23
  • will this work in php also because i tried but not working – Manish Kumar Nov 20 '15 at 13:35
  • In PHP, there is `preg_quote()`. – Wiktor Stribiżew Nov 20 '15 at 13:36
  • i tried `$pattern = "/[+-=> – Manish Kumar Nov 20 '15 at 13:43
  • Could you please specify the exact ptoblem you have? Why escaping `&&` as `\&&`? Your question is somewhat unclear and this is why I decided to close it. You say *I want to prepand ``\`` before all special characters* and the title says *Escaping special character considering two character as one*. Also, `preg_quote` escapes separate symbols that must be escaped for regex and you can specify more as the second parameter. If you want to replace, use `preg_replace` – Wiktor Stribiżew Nov 20 '15 at 17:44

0 Answers0