Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant seem to match Exact string with Preg_replace

Im trying to exactly match a string using the preg_replace function in php. I only want to match instances that have a single '@' symbol. I also require a variable to be passed in as a pattern.

$x = "@hello, @@hello, @hello, @@hello"
$temp = '@hello'

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

the result should just be:

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

Thank you in advance.

like image 804
sagnew Avatar asked Sep 27 '22 17:09

sagnew


1 Answers

Add a negative look-behind (?<!@) that will fail a match if the $temp is preceded with @ (or, in plain words, if there is a @ before @hello, do not match it):

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

See IDEONE demo

And here is a regex demo

Also, if you have whole word boundary at the end, append \b to the end of the pattern just to ensure you do not replace @helloween:

"/(?<!@)".$temp."\\b/"
like image 91
Wiktor Stribiżew Avatar answered Sep 30 '22 08:09

Wiktor Stribiżew