Replace Multiple Backslash Character Using preg_replace() in PHP

It seems like an easy problem to solve, but It’s not as easy as it seems. Assuming I have this string in PHP:

\\\super\\\\\\man\\\

and I would like to replace all the backslashes into space or other characters is not as easy as using str_replace() function. The number of backslashes may be 1 or more. But all consecutive need to be replace into ONE space.

The alternative solution is by using regular expression a.k.a Regex. PHP offer many regular expression-related function. One of them is preg_replace(). Those function are PERL compatible regular expression used to replace any string matched by a regular expression pattern into another string. More information about PHP preg_replace() function go here.

As an example, a regular expression pattern used to match a newline character are as follow:

"/\n/"

the n character must be escaped properly with a backslash. But, if you need to capture a backslash string which is followed by n character (“\n”) that is not a newline whitespace, then you have to escape the backslash as well using another backslash. The regex pattern to capture then should be modified to:

"/\\n/"

The first slash and the last slash are used as a regular expression delimiter. These delimiter may be replaced by another unused character on your regex pattern. For example, a tilde ‘~’ or backtick ‘`’ character.

Back to the main problem. In order to replace one or more consecutive backslash, you have to escape the escaping backslash and the backslash character itself with a backslash and followed by a plus ‘+’ character to denote that one or more previous character will be captured. The regex pattern then would become like this:

"~(\\\\)+~"

So if I have a string variable $content which requires to be cleaned up, the function should be like the following:

$content = preg_replace("~(\\\\)+~", "|", $content);

If the following string cleaned up using our previous regular expression pattern:

\\\super\\\\\\man\\\

Then it would become like:

|super|man|