2016-11-24 73 views
0

我試圖用2個解碼的html字符替換一個十進制數。我知道我需要使用正則表達式,但無法正確寫入。 我的字符串:Php正則表達式更改特殊字符之間的十進制數

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

我需要改變的是5.00與其他的十進制數。

我已經試過了:

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

回答

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

對方回答不會在大多數情況下,更換將無法正常工作它會嘗試訪問不存在的$ 17捕獲。

0

你應該試試這個:

$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; 
0

你可以使用lookaround

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