Seems to be relatively simple task that gets me stuck in one PHP application. I have a string which has a bunch of in it. Those are fine and need to stay there. However, there are also single occurrences of the character
\
and those I need to replace or remove, let's just say with empty character without removing the ones that are followed by n
.
The best I came up with was to first replace all with something else, some weird character, then replace the remaining
\
with empty space and then convert back the weird character to . However, that seems to be a waste of time and resources, besides, nothing guarantees me that I'll find weird enough character that will never be encountered in the rest of the string...
Any tips?
You need
$s = preg_replace('~\\\\(?!n)~', '', $s);
See the PHP demo:
$s = '\
\\t \\';
$s = preg_replace('~\\\\(?!n)~', '', $s);
echo $s; // =>
t
We need 4 backslashes to pass 2 literal backslashes to the regex engine to match 1 literal backslash in the input string. The (?!n)
is a negative lookahead that fails all matches of a backslash that is immediately followed with n
.
You should be able to do this with a negative lookahead assertion:
\\(?!n)
The \\
looks for the backslash, the (?!n)
asserts that the next character is not an n, but does not match the character.
To use this in PHP:
$text = 'foo
bar
b\az
';
$newtext = preg_replace('/\\\\(?!n)/', '', $text);
Details here: https://regex101.com/r/F2qhAP/1