Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Escape with Negative Lookahead

I have the following JSON-encoded string:

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

What is the most efficient way to escape all the (already) escaped chars / codepoints except \\\u0022 or \\\u0027? I though about using preg_replace() with a negative lookahead regular expression but it's not working as I expected, the output should be:

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

I'm feeling lost in this ocean of JSON-PHP-PCRE escaping, can someone help me out?

like image 395
Alix Axel Avatar asked Nov 22 '25 07:11

Alix Axel


2 Answers

Something like this may work with the help of negative lookahead:

<?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|""
like image 78
anubhava Avatar answered Nov 23 '25 22:11

anubhava


I'm a bit confused by exactly what you are trying to do but I can transform your input to your output with this:

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

Note: I'm not at my computer so I can't verify that this is perfect but it looks good from here.

like image 27
UnkwnTech Avatar answered Nov 24 '25 00:11

UnkwnTech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!