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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.