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.
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/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With