Php 用于向字符串中添加斜杠(该字符串中的第一个斜杠除外)的正则表达式
我有PHP中的字符串,如:Php 用于向字符串中添加斜杠(该字符串中的第一个斜杠除外)的正则表达式,php,preg-replace,Php,Preg Replace,我有PHP中的字符串,如: "%\u0410222\u0410\u0410%" 我需要通过添加斜杠来修改字符串,如: "%\u0410222\\\\u0410\\\\u0410%" (为字符串中的每个斜杠添加3个斜杠,第一个斜杠除外) 我想在这种情况下使用PHP preg_替换,以及如何编写正则表达式?正则表达式方式: $result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
"%\u0410222\u0410\u0410%"
我需要通过添加斜杠来修改字符串,如:
"%\u0410222\\\\u0410\\\\u0410%"
(为字符串中的每个斜杠添加3个斜杠,第一个斜杠除外)
我想在这种情况下使用PHP preg_替换,以及如何编写正则表达式?正则表达式方式:
$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
请注意,要在单引号模式中显示文字反斜杠,您需要使用至少3个反斜杠或4个反斜杠来消除歧义(在本例中,例如\K
)。使用nowdoc语法,只需要两个,如详细版本中所示:
$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;
正则表达式方式:
$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
请注意,要在单引号模式中显示文字反斜杠,您需要使用至少3个反斜杠或4个反斜杠来消除歧义(在本例中,例如\K
)。使用nowdoc语法,只需要两个,如详细版本中所示:
$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;
正则表达式方式:
$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
请注意,要在单引号模式中显示文字反斜杠,您需要使用至少3个反斜杠或4个反斜杠来消除歧义(在本例中,例如\K
)。使用nowdoc语法,只需要两个,如详细版本中所示:
$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;
正则表达式方式:
$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);
请注意,要在单引号模式中显示文字反斜杠,您需要使用至少3个反斜杠或4个反斜杠来消除歧义(在本例中,例如\K
)。使用nowdoc语法,只需要两个,如详细版本中所示:
$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;
可能更容易对所有斜杠执行1->3,然后对第一个斜杠执行3->1。可能更容易对所有斜杠执行1->3,然后对第一个斜杠执行3->1。可能更容易对所有斜杠执行1->3,然后对第一个斜杠执行3->1。可能更容易对所有斜杠执行1->3,然后对第一个斜杠执行3->1。