Search code examples
phpregexpreg-replacespecial-characters

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


Solution

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

    Try this.This is working.