开发者

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 \\\u0开发者_开发百科022 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);
?>

OUTPUT

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.


Try

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

This finds a \ only if it is single (i. e. neither preceded nor followed by another \) and replaces it with \\\.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜