john BB
john BB

Reputation: 79

Regular expression for adding slashes to string, except first slash in that string

I have string in PHP, like:

"%\u0410222\u0410\u0410%"

And I need to modify the string by adding slashes like:

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

(add 3 slashes for each slash in string, except first slash) I want to use PHP preg_replace for this case, and how to write regular expression?

Upvotes: 0

Views: 256

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

A regex way:

$result = preg_replace('~(?:\G(?!\A)|\A[^\\\]*\\\)[^\\\]*\\\\\K~', '\\\\\\\\\\', $txt);

Note that to figure a literal backslash in a single quoted pattern, you need to use at least 3 backslashes or 4 backslashes for disambiguation (in this case for example \\\\\K). With the nowdoc syntax, only two are needed as you can see in detailed version:

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

Without regex:(maybe more efficient):

$chunks = explode('\\', $txt);
$first = array_shift($chunks);
$result = $first . '\\'. implode('\\\\\\\\', $chunks);

Upvotes: 3

Related Questions