Regular expression to remove duplicate slash

How are you? I have the following challenge. I have a lot of lines that may contain duplicate slashes. I need to replace the duplicate forward slashes with a single forward slash (any number of forward slashes), but when the following characters are found after the forward slashes (quote, double quote, NUL (NULL bytes)), all the slashes must be removed. Thank you. My language is PHP. Some tests:

$s1 = 'test\\\\string';
// test\string
$s2 = 'test\\\\\"\\\\\'\\\\string';
// test"'\string
$s3 = 'test\\string\\\\\"';
// test\string"

      

+3


source to share


5 answers


Use

preg_replace("~\\\\+([\"\'\\x00\\\\])~", "$1", $string);

      

to replace arbitrary amounts with \

just one \

.

The template consists of arbitrary initial reverse side \\\\+

, and the next character, which is one of "

, '

, \x00

or \

. The replacement will effectively remove any obstructing back surfaces.

You need 4 backslashes in your regex. Two backslashes ( \\

) will result in one backslash ( \

) within the regex string because the PHP interpreter uses backslashes to escape special characters like "

or \

. For the same reason, you will need two backslahes inside your regex.



Or explained another way: To get \+

as a regex you need to add a backslash to tell PCRE that a single backslash is not for escaping +

. To get \\+

as a string, you'll also need to add one backslash before each backslash to tell the PHP interpreter that you don't want to escape the second backslash from the first.

source: \\\\+

inside the regex string: \\+

: \+

+4


source


Replace 2 or more consecutive slashes with one forward slash preg_replace('/\\\\+/','\\',$str);



+2


source


Alternative way.

$s = 't\est\\\\\\\\\\\\stri\\\\\"\\\\\'\\\\0\\\\ng';
$s = preg_replace('~\\\\+~', '\\', $s);
$s = str_replace(array('\\"', '\\\'', '\\0'), array('"', '\'', "\0"), $s);

      

+2


source


Try the following:

preg_replace("/\\+(['\"\0\\])/", "$1", $string);

      

+1


source


What happened to the stripslashes ? It takes into account the forward slashes that come out of the "special" character and removes the "extra" forward slashes.

0


source







All Articles