How do i replace an expression with metacharacters using preg_replace in PHP?
I've tried in different ways, replacing a excerpt of text with metacharacters with another text with metacharacters in PHP. I know, it seems very simple but i've tried many times but didn't get it.
pattern: $Sel = 'anyvalues';
replacement: $Sel = 'one other';
subject: <?php $Sel = 'anyvalues';
I deeply tried using addslashes() and preg_quote() methods in different orders but it doesn't work. I need it to be as represented instead of looking for any workarounds.
Each one of these values lie in different files, i.e., the pattern lies in one file, replacement in another one, and subject in another as well.
Have you wrapped your pattern in delimiters?
$pattern = '$Sel = "anyvalues_containing_delimiter_/";';
$replacement = '$Sel = "one other";';
$subject = '<?php $Sel = "anyvalues_containing_delimiter_/";';
echo preg_replace(sprintf('/%s/', preg_quote($pattern, '/')), $replacement, $subject);
The contents of pattern are the only ones that need escaping, hence the preg_quote
call. Second argument is the delimiter in which the pattern is wrapped (what sprintf
does here), so any occurences within the pattern content can also be escaped before they are applied.
Edit: I've modified the snippet to cover for occurences of the delimiter within file contents.
Second edit: moved code from linked snippet into the answer itself.