Bastian Globig
Bastian Globig

Reputation: 45

PHP preg_replace unexpected Output in case of matching special Character '$'

I got an Issue in a PHP Script, in case of this function for regular expression matching and replacing. I've tested my regular Expression on www.regex101.com and got always expected results, but not in PHP.

I use this Pattern inside the Function:

$matchedName = preg_replace("/^(\$|\(.+\))( ?)/", "", $name);

To match Character '$' or any Expression in Brackets at the Begin and delete this. Any Input with Brackets works well.

$name = "$ blah";
$matchedName = preg_replace("/^(\$|\(.+\))( ?)/", "", $name);
var_dump($matchedName);

Output:
string(8) "$ blah"

Now, got i missunderstood something? Or got this Function really an Issue in Case of the '$' Character?

Thanks for any Replies

Upvotes: 0

Views: 201

Answers (2)

elixenide
elixenide

Reputation: 44833

You need to escape the \, so your code should be:

$name = "$ blah";
$regex = "/^(\\\$|\(.+\))( ?)/";
$matchedName = preg_replace($regex, "", $name);

var_dump($regex);
var_dump($matchedName);

Demo

The problem is that you are in double quotes ("..."), so the PHP interpreter interprets the first \ as merely escaping the $ within the string, not as a literal \. It needs to be a literal \ for purposes of escaping a character in a regex.

Your actual regex therefore looks like this, after the processor interprets it: /^($|\(.+\))( ?)/. You need to escape the $ inside double quotes and provide a slash in the regex context, so you add \\.

Note that you could avoid this by simply using single quotes ('...') instead, and you would only need \$ instead of \\\$:

$name = "$ blah";
$regex = '/^(\$|\(.+\))( ?)/';
$matchedName = preg_replace($regex, "", $name);

var_dump($regex);
var_dump($matchedName);

Demo

Upvotes: 2

vks
vks

Reputation: 67968

$re = "/^(\\$|\\(.+\\))( ?)/im";
$str = "\$ blah";
$subst = "";

$result = preg_replace($re, $subst, $str);

Try this.This is working.

Upvotes: 0

Related Questions