Re: preg_replace - I don't have a clue

From: Date: Fri, 13 Jan 2006 22:00:00 +0000
Subject: Re: preg_replace - I don't have a clue
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-228592@lists.php.net to get a copy of this message
Is this the wrong forum for this question - or does no-one else have a clue about this either? At 09:43 AM 1/12/06, Frank Bax wrote:
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.
preg_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 :
preg_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 (#228592) next »