Dejavu
Dejavu

Reputation: 713

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);

Upvotes: 0

Views: 66

Answers (3)

Toto
Toto

Reputation: 91385

You could use lookaround

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

Upvotes: 0

Max
Max

Reputation: 891

You should try this :

$re = '/(class="total">)([0-9]+\.?[0-9]+)(<\/td>)/';
$str = 'class="total">5.00</td>';
$subst = '${1}7.00${3}';

$result = preg_replace($re, $subst, $str);

echo $result;

Upvotes: 0

Enstage
Enstage

Reputation: 2126

$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.

Upvotes: 1

Related Questions