Cant seems to match Exact string with Preg_replace

Im trying to exactly match the string using the preg_replace function in php. I only want to match instances with a single "@" character. I also require that the variable be passed as a template.

$x = "@hello, @@hello, @hello, @@hello" $temp = '@hello' $x = preg_replace("/".$temp."/", "replaced", $x); 

the result should only be:

 $x = "replaced, @@hello, replaced, @@hello" 

Thanks in advance.

+5
source share
1 answer

Add a negative look-behind (?< !@ ) that won't be able to match if $temp precedes @ (or, in simple words, if there is @ before @hello , don't match):

 $x = "@hello, @@hello, @hello, @@hello"; $temp = '@hello'; $x = preg_replace("/(?< !@ )".$temp."/", "replaced", $x); echo $x; 

Watch the IDEONE demo

And here is the demo version of regex

Also, if you have a whole word boundary at the end, add \b to the end of the pattern to make sure you don't replace @helloween :

 "/(?< !@ )".$temp."\\b/" 
+4
source

All Articles