Issue
E.g. in the code below, if the user wants the new content of the template to be the string C:\Users\Admin\1, the \1 part will become BEGIN this was the original content of the template END, which is something I don't want.
preg_replace('/(BEGIN.*?END)/su', $_POST['content'], $template);
Solution
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).
Answered By - Wiktor Stribiżew Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.