0

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?

1
  • 1
    probably easier to do the 1->3 for all slashes, then do a 3->1 for the first one. Commented Aug 24, 2015 at 16:18

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.