I am investigating, but I am not able to find the solution to this.
The idea is to replace the characters $_ from a string with something else.
If you remove the dollar sign from the $search variable, it kind of works (but not in a desirable way).
It is not working because the dollar sign is a special character, but I cannot find how to scape it.
This is what I have:
$search = '$_'; // replace to '_' OR '[$_]' it returs "$1" instead of "1"
$replace = 1;
$regex = '#".*?"(*SKIP)(*FAIL)|\b' . $search . '\b#s';
$fullInput = '"$_" $_';
$r = preg_replace([$regex], $replace, $fullInput);
echo $r . PHP_EOL;
// Output with current code : "$_" $_
// Output with '_' or '[$_]': "$_" $1
//
// Expected result: "$_" 1
To have into account, if the text is between quotes, it should not be replaced.
You may use this regex for search:
"[^\\"]*(?:\\.|[^\\"]*)*"(*SKIP)(*F)|\$_
and replace it with [$0]
Pattern before | matches a double quoted string allowing an escaped quote in between. Pattern after | matches $_.
RegEx Details:
"[^\\"]*(?:\\.|[^\\"]*)*": Match a double quoted string. We allow escaped characters in this match.(*SKIP)(*F): Skip and fail this match|: OR\$_: Match literal text $_Code:
$search = '$_';
$replace = '[$0]';
$regex = '/"[^\\"]*(?:\\.|[^\\"]*)*"(*SKIP)(*F)|' . preg_quote($search, '/') . '/';
$fullInput = '"$_" $_';
$r = preg_replace($regex, $replace, $fullInput);
echo $r . PHP_EOL;
Output:
"$_" [$_]