note 23564 deleted from function.preg-replace by sniper

From: Date: Tue, 30 Sep 2003 12:31:09 +0000
Subject: note 23564 deleted from function.preg-replace by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57475@lists.php.net to get a copy of this message
Note Submitter: guidod@gmx.de ---- PERL programmer will be greatly confused by the way the /e works. The following two assumptions are _wrong_: * the eval will be in the context of the surrounding functions where you access its variables. The following will fail: _replace('/(...)/e','my_func($F)',$T); The $F-variable-ref in the eval is empty! * the $1..$n are global variables. This one will fail too: _replace('/(..)/e','my_func("hello",$1),$T); The docs above say: " /e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. " - this is way to short and should be clarified!! Lets look at the replace-arg of the following example: _replace('/(\w+) .*/e',"my_func('$F','$1','$2',"hey you"); and this really happens: (1) the doublequotes are interpolated before 'replace' will see its arguments - replace-arg is now: "my_func('file.out','$1',' $2')" (2) the 'replace' takes its arguments and interpolates occurences of $1 through $n in the replacetext. The result is now: "my_func('file.out','hey',' you')" (3) the sequence above happens always, but if there is an /e additionally then the result will be sent additionally into an 'eval'. Therefore, the perl programmer's assumptions will fail in some places: (a) using single-quotes around the replace-arg will let the $F get to the final /eval which where the outer $F-variable is unaccessible and therefore empty. The functions variables are not accessible from the /eval, better let it get interpolated into the arg-replace-string beforehand, in step (1) (b) forgetting to place $1 in singlequotes (or atleast doublequotes) will make the php-parser (of eval) try to interpret hey and you, and make a problem about it. These $#'s are not variables, they are just interpolation points of 'replace' and the resulting text (!) might be later subject to the php-parser run in the additional /e-eval. ==> As a recommended habit: put the /e-replacetext in doublequotes and _all_ arguments to the function therein should be in singlequotes to prevent it from a double interpolation. (No need to fiddle with the escaped-doublequotes as shown in the user-contributed notes above.)

« previous php.notes (#57475) next »