【问题标题】:Regular expression for adding slashes to string, except first slash in that string用于向字符串添加斜杠的正则表达式,该字符串中的第一个斜杠除外
【发布时间】:2015-11-18 03:42:39
【问题描述】:

我在 PHP 中有字符串,例如:

"%\u0410222\u0410\u0410%"

我需要通过添加斜杠来修改字符串:

"%\u0410222\\\\u0410\\\\u0410%"

(为字符串中的每个斜杠添加 3 个斜杠,第一个斜杠除外) 我想在这种情况下使用PHP preg_replace,以及如何编写正则表达式?

【问题讨论】:

  • 可能更容易对所有斜杠执行 1->3,然后对第一个斜杠执行 3->1。

标签: php preg-replace


【解决方案1】:

正则表达式方式:

$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);

【讨论】:

    猜你喜欢
    • 2015-07-14
    • 2018-02-27
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多