1

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?

2
  • 2
    Use single-quoted string literal to avoid string interpolation. Same with regex, use single quotes. Commented Aug 31, 2017 at 8:01
  • Thank you, replacing double quotes with single quotes in the regex did it. Commented Aug 31, 2017 at 8:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.