I’m having issues replacing a tag within a message where the tag begins with a $ character.
Here’s the code I’m trying to use:
$tag = '$TAG';
$message = '..text $TAGd d$TAG $TAG text..';
$pattern = '/\b\\'.$tag.'\b/';
echo $pattern."<br/>";
echo preg_replace($pattern, "REPLACED", $message);
output:
/\b\$TAG\b/
..text $TAGd dREPLACED $TAG text..
I want it to replace the last occurance of $TAG since it’s the only one not obstructed by additional characters. However it keeps replacing the 2nd one no matter what I try.
Some variations that I’ve tried:
Skipping the $tag variable string concatination
$message = '..text $TAGd d$TAG $TAG text..';
$pattern = '/\b\$TAG\b/';
echo $pattern."<br/>";
echo preg_replace($pattern, "REPLACED", $message);
output:
/\b\$TAG\b/
..text $TAGd dREPLACED $TAG text..
Removing the backslash before $
$message = '..text $TAGd d$TAG $TAG text..';
$pattern = '/\b$TAG\b/';
echo $pattern."<br/>";
echo preg_replace($pattern, "REPLACED", $message);
output:
/\b\$TAG\b/
..text $TAGd d$TAG $TAG text..
Adding a second backslash before $
$message = '..text $TAGd d$TAG $TAG text..';
$pattern = '/\b\\$TAG\b/';
echo $pattern."<br/>";
echo preg_replace($pattern, "REPLACED", $message);
output:
/\b\$TAG\b/
..text $TAGd dREPLACED $TAG text..
Any help regarding this issue will be much appreciated, since I don’t seem able to wrap my mind around what I’m doing wrong. Thank you! 🙂
Use
\Bfor beginning of word and\bfor end of word:worked fine for me. I’m not sure why this is the case, as normally it should be just
\b– but it did solve the issue.