用于向字符串添加斜杠的正则表达式,除了该字符串中的第一个斜杠
Regular expression for adding slashes to string, except first slash in that string
我在 PHP 中有字符串,例如:
"%\u0410222\u0410\u0410%"
我需要通过添加斜杠来修改字符串,例如:
"%\u0410222\\u0410\\u0410%"
(字符串中除第一个斜线外,每个斜线加 3 个斜线)
这种情况我想用PHP preg_replace,正则表达式怎么写?
正则表达式方式:
$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;
没有正则表达式:(可能更有效):
$chunks = explode('\', $txt);
$first = array_shift($chunks);
$result = $first . '\'. implode('\\\\', $chunks);
我在 PHP 中有字符串,例如:
"%\u0410222\u0410\u0410%"
我需要通过添加斜杠来修改字符串,例如:
"%\u0410222\\u0410\\u0410%"
(字符串中除第一个斜线外,每个斜线加 3 个斜线) 这种情况我想用PHP preg_replace,正则表达式怎么写?
正则表达式方式:
$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;
没有正则表达式:(可能更有效):
$chunks = explode('\', $txt);
$first = array_shift($chunks);
$result = $first . '\'. implode('\\\\', $chunks);