简体   繁体   English

正则表达式 - 逃避负面前瞻

[英]Regex - Escape with Negative Lookahead

I have the following JSON-encoded string: 我有以下JSON编码的字符串:

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

What is the most efficient way to escape all the (already) escaped chars / codepoints except \\\\" or \\\\\' ? 除了\\\\"\\\\\' \\\\"之外 ,最有效的方法是逃避所有 (已经)转义的字符/代码点? I though about using preg_replace() with a negative lookahead regular expression but it's not working as I expected, the output should be: 我虽然使用带有负前瞻正则表达式的preg_replace()但是它没有按照我的预期工作,输出应该是:

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

I'm feeling lost in this ocean of JSON-PHP-PCRE escaping, can someone help me out? 我在JSON-PHP-PCRE逃离的这片海洋中感到迷茫,有人可以帮助我吗?

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 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 (ie neither preceded nor followed by another \\ ) and replaces it with \\\\\\ . 这个发现一个\\仅当它是单(即,既不之前也不是由另一随后\\ ),并用其替换\\\\\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM