PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How to quote replacement in preg_replace?

 November 19, 2022     php, preg-replace, regex     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing