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?
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);
?>
string(25) ""|\t|\n|\\u0027|\\u0022|""
string(29) ""|\\\t|\\\n|\\u0027|\\u0022|""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With