a1277399
a1277399

Reputation: 27

Unexpected result with preg_replace()

$subject = "'foo' = 'bar'";
$pattern = "/('foo' = ').*(')/";
$var = "123baz";
$replacement = "$1$var$2";
print_r(preg_replace($pattern, $replacement, $subject));

Result is 23baz' instead of 'foo' = '123baz'. Why and how can I fix this?

Upvotes: 1

Views: 67

Answers (1)

Rizier123
Rizier123

Reputation: 59681

Think you're looking for something like this:

$subject = "'foo' = 'bar'";
$pattern = "/(= ').*(')/";
$var = "123baz";
$replacement = "= '$var'";
print_r(preg_replace($pattern, $replacement, $subject));

Output:

'foo' = '123baz'

Upvotes: 2

Related Questions