Jeff
Jeff

Reputation: 6110

preg_replace cannot perform simple math in the replacement

I've tried all kinds of different sequences and escaping, but no luck. Preg_replace is ignoring the $i and using the integer after the + as its' replacement.

First Example:

$i = 1;
$s = preg_replace( '/\[$/', '${' . $i + 1 . ':[', $s );
var_dump( $s );

Result: ${1:[ // should be 2

Second Example:

$i = 1;
$s = preg_replace( '/\[$/', '${' . $i + 9 . ':[', $s );
var_dump( $s );

Result: ${9:[ // should be 10

Without addition it works fine:

$i = 12;
$s = preg_replace( '/\[$/', '${' . $i . ':[', $s );
var_dump( $s );

Result: ${12:[ // okay

Upvotes: 0

Views: 262

Answers (1)

nickb
nickb

Reputation: 59699

You need parenthesis to group the expression so that the addition happens before the concatenation.

$s = preg_replace( '/\[$/', '${' . ($i + 1) . ':[', $s );

Upvotes: 1

Related Questions