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

Sunday, November 20, 2022

[FIXED] How to make this preg_replace work with these character replacement?

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

Issue

Hi,

I am struggling to understand the logic in regular expressions. I have this code:

preg_replace("~\b$replace\b~","",$file);

Where $replace is a numeric value but it should be encapsulated inside [] to look like this: [33] so I did this:

preg_replace("~\b[$replace]\b~","",$file);

and this:

$replace = "[".$value."]";
preg_replace("~\b[$replace]\b~","",$file);

but none will parse. What is the logic behind this?

Thank you.


Solution

Square brackets have special meaning in regular expressions, so you need to escape them to match them literally.

You shouldn't use \b around the square brackets. \b matches a word boundary, which means a word character next to a non-word character. So unless there's an alphanumeric character before the [ and after ], it won't match.

preg_replace("~\[$replace\]", "", $file);

And once you've done that, you don't actually need to use preg_replace(). This is just a fixed string with no regexp patterns, so just use str_replace()

str_replace("[$replace]", "", $file);


Answered By - Barmar
Answer Checked By - Senaida (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