I want to do some custom character escaping which means I want some characters to be preceded with some special character only if they are not already preceded by that special character. I assume I am going to need a regex replace. What is the easiest way to achieve that? I tried something with negative lookbehind assertion and ended up with nothing.
EDIT: Imagine that I want any of abc
chars to be escaped with \
, so giving debby
I should get de\b\by
while out of da\bby
I want to make d\a\b\by
. I guess this example is not that creative, nevertheless I believe it explains what I mean (escape chars that are not yet escaped)
EDIT2: Well, what I am actually trying to do is to turn a string of
([A-Za-z]+)/([A-Za-z]+)/([A-Za-z]+)
into
([A-Za-z]+)\/([A-Za-z]+)\/([A-Za-z]+)
In the string number one the forward slash is, say, some kind of a delimiter (and I expect to have more of them later, I would also like to escape .
, ,
at the same time) which I need to escape with \
to use it as another (simpler) pattern. I tried (not sure about the second argument but that is not a problem I believe)
preg_replace("/(?<!\\)([\/])/", "\\$0", $string);
where $string
is ([A-Za-z]+)/([A-Za-z]+)/([A-Za-z]+)
. No luck.
Hope I made that clear now
SOLUTION:
preg_replace("/(?<!\\\\)[\/]/", "\\\\$0", $string);
in the square brackets I put the chars to be escaped.