To use a simplified example, I have:
$str = "Hello :special_text:! Look, I can write \:special_text:";
$pattern = /*???*/":special_text:";
$res = preg_replace($pattern, 'world', $str);
$res = str_replace("/:", ":", $res);
$res === "Hello world! Look, I can write :special_text:"; // => true
In other words, I’d like to be able to “escape” something that I’m writing.
I think that I have something almost working (using [^:]? as the first part of pattern), but I don’t think that works if $str === ":special_text:", in that^doesn't match[^:]?`.
You can use a negative lookbehind:
This says “replace a
:special_text:that isn’t preceded by a backslash”.In your second
str_replacelooks like you want to replace\:by:.See it in action here.
Also, don’t forget if you use backslash in PHP strings you need to escape them once more (if you want a literal
\you need to use PHP\\, and to get a literal\\you need to use PHP\\\\:Here the
@is just a regex delimiter.