In short, use this function to quote a dynamic replacement pattern:
function preg_quote_replacement($repl_str) {
return str_replace(array('\\', '$'), array('\\\\', '\\$'), $repl_str);
}
The thing is, you need to escape the backslash in the replacement pattern. See preg_replace
docs:
To use backslash in replacement, it must be doubled ("\\\\"
PHP string).
It can be done with a mere str_replace
function:
$repl = 'C:\Users\Admin\1';
$template = "BEGIN this was the original content of the template END";
echo preg_replace('/(BEGIN.*?END)/su', str_replace('\\', '\\\\', $repl), $template);
See IDEONE demo
However, NOTE that the $
symbol is also special in the replacement pattern. Thus, we also need to escape this symbol. The order of these prelimnary replacements matter: first, we need to escape the \
, and then the $
:
$r = '$1\1';
echo preg_replace('~(B.*?S)~', str_replace(array('\\', '$'), array('\\\\', '\\$'), $r), "BOSS");
See IDEONE demo (in your code, preg_replace('/(BEGIN.*?END)/su', str_replace(array('\\', '$'), array('\\\\', '\\$'), $_POST['content']), $template);
or use the function I added at the start of the post).
preg_replace('/(BEGIN.*?END)/su', str_replace('\\', '\\\\', $_POST['content']), $template);