PHP – Regex replacement throws an error (preg_replace)

I need to remove some weird characters in a string pulled from a source database using a regex because these characters can be located anywhere in the string and can be a little different.
Here’s my code right now:

$str = "LIVR DEC 20 23 $é**é$01$";
$result = preg_replace("//$[^ ]+/$/", "", $str);

When testing it on phpliveregex.com, it works fine but when i run the code (using PHP 5.4), i get the following error:

PHP Notice: Undefined variable: é

and $result contains the original string. Why is it throwing that error?

You need to define the $str and the regex inside single quoted string literals. Also, since you are working with Unicode strings, you should also use the u modifier:

$str = 'LIVR DEC 20 23 $é**é$01$';
$result = preg_replace('//$[^ ]+/$/u', "", $str);
echo $result; // => LIVR DEC 20 23

See the PHP demo.

Otherwise, when PHP engine sees “$é”, it wants to interpolate it, but cannot find the variable with this name.

The regex needs single quotes because “//$[^ ]+/$/” is equal to /$[^ ]+$/ where $ are end of string anchors, and there can’t be two different end-of-string positions inside a single string.

Or, if you need to use string iterpolation and use double quoted string literals, escape $ to denote a literal $ in the string, and escape the $ inside the regex with ///, triple backslashes (one escapes $ for the PHP engine, and // form a literal / that makes an escape symbol for regex special chars):

$str = "LIVR DEC 20 23 /$é**é$01/$";
$result = preg_replace("////$[^ ]+///$/u", "", $str);
echo $result; // => LIVR DEC 20 23

See another PHP demo.