using
$text = "LeftWidth = 16em\n";
preg_match_all('/([a-zA-Z]*)\s*=(\s*?)([ a-zA-Z0-9]*)\n/i', $text, $result);
$newvalue = "24em";
$text = preg_replace('/([a-zA-Z]*)\s*=(\s*?)([ a-zA-Z0-9]*)\n/i', "$1=$2_REMOVE_$newvalue", $text);
$text = str_replace("_REMOVE_",'',$text);
echo "[$text]<br />\n";
I can get the result you want.
The reason why this happens is because when the text is parsed the "newvalue" variable exists so it puts in "$1=$224em\n"
This is where preg_replace tries to parse it and may get confused by this. You could use a space instead of _REMOVE_ but then str_replace would so easily take out every space in the whole thing.