preg_replace - I don't have a clue

From: Date: Thu, 12 Jan 2006 14:43:24 +0000
Subject: preg_replace - I don't have a clue
Groups: php.general 
Request: Send a blank email to php-general+get-228527@lists.php.net to get a copy of this message
As I understand the docs for preg_replace(), I can enclose an PCRE expression in parenthesis and use a backreference in the replace string; but it's not working! Data coming from another system contains a lot of data in one text record which I must parse. Individual elements in the record are separated by $. I want to "fix" elements that contain
        dollar-alpha-space-space-digits-dollar
and replace the second space (between word and number) with a plus character to end up with
        dollar-alpha-space-plus-digits-dollar
An example of input string:
        $prop = '$Fencing  11$Lumber  17$Weight: 317 Stones$Energy Resist 2%$';
Notice that Fencing and Lumber have two spaces. I want to end up with:
        $prop = '$Fencing +11$Lumber +17$Weight: 317 Stones$Energy Resist 2%$';
Notice that original and final strings are the same length.
reg_replace( '  (\d+\$)', '+$1', $prop );       /* results in dollar-alpha-space-space-plus, why have digits-dollar have disappeared? */
$Fencing +Lumber +Weight: 317 Stones$Energy Resist 2%$ Although the docs say that $0 should backreference the whole pattern, instead it seems to match the pattern in parenthesis, but this code :
reg_replace( '  (\d+\$)', '+$0', $prop );       /* results in dollar-alpha-space-space-plus-digits-dollar */
$Fencing +11$Lumber +17$Weight: 317 Stones$Energy Resist 2%$ Still contains the two blanks!! In neither of my test cases is the result string the same length as original. I'm running PHP 4.4.0 on OpenBSD 3.7

« previous php.general (#228527) next »