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

Sunday, November 20, 2022

[FIXED] How do i replace an expression with metacharacters using preg_replace in PHP?

 November 20, 2022     php, preg-replace     No comments   

Issue

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.


Solution

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.



Answered By - El_Vanja
Answer Checked By - Cary Denson (PHPFixing Admin)
  • 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