regex - Replace a word which contains a $ character in PHP -


i'm having issues replacing tag within message tag begins $ character.

here's code i'm trying 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 replace last occurance of $tag since it's 1 not obstructed additional characters. keeps replacing 2nd 1 no matter try.

some variations i've tried: skipping $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 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 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 regarding issue appreciated, since don't seem able wrap mind around i'm doing wrong. thank you! :)

use \b beginning of word , \b end of word:

$tag = '$tag'; $message = '..text $tagd d$tag $tag text..'; $pattern = '/\b\\'.$tag.'\b/'; echo $pattern."<br/>"; echo preg_replace($pattern, "replaced", $message); 

worked fine me. i'm not sure why case, should \b - did solve issue.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -