Here is my dilemma:
I wrote this RegEx pattern which works in my sandbox but does not work on my website:
Sandbox: http://regex101.com/r/vP3uG4
Pattern:<
If the variable $value contains a numerical value then the replacement pattern in your preg_replace will look like this: $12$3
That's true but not as you expected. In Regex Engine, $ffffd or here $dd (which are equal to \ffffd and \dd) are treated as octal numbers.
So in this case $12 means a octal index 12 which is equal to a kind of space in ASCII.
In the case of working with these tricky issues in Regular Expressions you should wrap your backreference number within {} so it should be ${1}2${3}
Change your replacement pattern to '${1}'.$value.'${3}'
Okay, found out the issue. The solution is to wrap the backreference in ${}.
Quoting the PHP manual:
When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar
\\1notation for your backreference.\\11, for example, would confuse preg_replace() since it does not know whether you want the\\1backreference followed by a literal1, or the\\11backreference followed by nothing. In this case the solution is to use\${1}1.
So, your code should look like:
header('Content-Type: text/plain');
$variable = 'tbs_development';
$value = '333';
$savedsettings_temp = <<<'CODE'
$tbs_underconstruction = 'foo';
$tbs_development = 0;
CODE;
$pattern = '/(.*[$]'.preg_quote($variable).'\s*=\s*\'?)(.*?)(\'?;.*)/is';
$replacement = '${1}'.$value.'${3}';
$savedsettings_new = preg_replace($pattern, $replacement, $savedsettings_temp);
echo $savedsettings_new;
Output:
$tbs_underconstruction = 'foo';
$tbs_development = 333;
Demo.