Dejavu Dejavu - 12 days ago 8
PHP Question

Php regex change a decimal number between special characters

I am trying to replace a decimal number between 2 decoded html characters. I know I need to use regex for this but couldn't write it properly.
my string:

$string = 'class="total">5.00</td>';


What I need to change is 5.00 with another decimal number.

I've tried that:

$string = 'class="total">5.00</td>';
$new_number = 7.00;
echo preg_replace('#\class="total">(.+?)\</td>#', $new_number, $string);

Answer
$string = 'class="total">5.00</td>';
$replacement = '6.00';
echo preg_replace('/(class="total">)(\d+\.\d{1,2})(<\/td>)/', '${1}' . $replacement . '${3}', $string);

The other answer won't work in most cases, the replacement won't work as it will try to access $17 capture which doesn't exist.