|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2019-11-08 03:01 UTC] markem at sim1 dot us
Description: ------------ --- From manual page: https://php.net/function.preg-replace --- I was working on correcting a function by dawidgarus at gmail dot com. Got it working (yeah!). But then decided to write my own and expand upon it. That was when I ran into this problem: If you use preg_replace, the "replace" string can not use the $x or ${x} within another variable (like an array). This generates an error. Test script: --------------- function bc() { $argv = func_get_args(); $cmd = $argv[0]; $cmd = preg_replace( "/\$(\d+)/", $argv[$1], $cmd ); return( $cmd ); } $a = bc( "sqrt($1*$1+$2*$2)", 3, 5 ); Expected result: ---------------- $a should equal "sqrt(3*3+5*5)" Actual result: -------------- Notice: Undefined variable: i in C:\Users\Mark\My Programs\PHP\lib\bcd.php on line ### PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 08:00:01 2025 UTC |
Hey! Not asking for help with a program - reporting a bug. I noted that it said "i" instead of "1". Was hoping you guys would understand. But no - so here is another test program. Same problem: <?php $s = $argv[1]; $s = preg_replace( "/\$(\d+)/", $argv[$1], $s ); echo "S = $s\n"; ?> Test command: c:>php test.php "sqrt(($1*$1)+($2*$2))" 3 5 Result: Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in C:\test.php on line 4 shell returned 255 Please note the '1'. That '1' is being put inside of the "$argv", this should be "$argv[1]" but instead, the '$' in front of the '1' causes PHP to think it is a variable which produces the error. Better? Sorry for the mis-post the first time. Tried to edit it but that did not work. By the way: The ORIGINAL source code had "/\$(\d+)/e" which the "e" option is no longer supported in preg_replace. The only way to take care of this is to use the preg_replace_callback() function. BUT! I thought that PHP should be able to use the '$1' and correctly substitute the found value in the replacement section. ALSO BTW : If you change the replacement area with "$argv[${1}]" - PHP still complains: Source: <?php $s = $argv[1]; $s = preg_replace( "/\$(\d+)/", $argv[${1}], $s ); echo "S = $s\n"; ?> command: php test.php "sqrt(($1*$1)+($2*$2))" 3 5 Results: C:\>php test.php "sqrt(($1*$1)+($2*$2))" 3 5 Notice: Undefined variable: 1 in C:\test.php on line 4 Notice: Undefined index: in C:\test.php on line 4 S = sqrt(($1*$1)+($2*$2)) Sorry for the botched post earlier. Hopefully this one shows you what I mean. :-)