Regex - Escape with a negative look

I have the following JSON encoded line:

$json = '"|\t|\n|\\\u0027|\\\u0022|"';

What is the most efficient way to avoid all (already) escaped characters / code points except \\\u0022or \\\u0027? . Although I used preg_replace()with a negative regex, but it does not work as I expected, the output should be:

$json = '"|\\\t|\\\n|\\\u0027|\\\u0022|"';

I feel lost in this ocean of survival JSON-PHP-PCRE, can someone help me?

+3
source share
3 answers

Something like this might work with a negative view:

<?php
  $json = '"|\t|\n|\\\u0027|\\\u0022|"';
  $s = preg_replace('~(\\\\)(?!(\\1|u002[27]))~', '$1$1$1', $json);
  var_dump($json);
  var_dump($s);
?>

OUTPUT

string(25) ""|\t|\n|\\u0027|\\u0022|""
string(29) ""|\\\t|\\\n|\\u0027|\\u0022|""
+2
source

I am a little confused by what you are trying to do, but I can convert your input to your output with this:

preg_replace('/\|\\([^\\])\|/', '\\\\\\$1|', $json);

. , , , .

+1

Try

$result = preg_replace('/(?<!\\\\)\\\\(?!\\\\)/', '\\\\\\\\\', $subject);

This is found \only if it is one (that is, does not precede and does not follow another \) and replaces it with \\\.

+1
source

All Articles