我在PHP中有字符串,如:
"%\u0410222\u0410\u0410%"
我需要通过添加斜杠来修改字符串,如:
"%\u0410222\\\\u0410\\\\u0410%"
(为字符串中的每个斜杠添加3个斜杠,第一个斜杠除外) 我想在这种情况下使用PHP preg_replace,以及如何编写正则表达式?
答案 0 :(得分:3)
正则表达方式:
echo
请注意,要在单个引用模式中计算文字反斜杠,您需要使用至少3个反斜杠或4个反斜杠来消除歧义(在本例中为$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
)。使用nowdoc语法,只需要两个,如详细版本所示:
\\\\\K
没有正则表达式:(可能更有效率):
$pattern = <<<'EOD'
~ # pattern delimiter
(?:
\G # position after the previous match
(?!\A) # not at the start of the string
| # OR
\A # start of the string
[^\\]* # all that is not a slash
\\ # a literal slash character
)
[^\\]* \\
\K # discard all on the left from the match result
~x
EOD;