Reputation: 3085
I have a string which contains several different prices. This is the string:
<div class="price-box">
<p class="old-price">
<span class="price" id="old-price-145">
ab 64,00 € *
</span>
</p>
<p class="special-price">
<span class="price" id="product-price-145">
ab 27,00 € *
</span>
</p>
I want to replace only the 27,00 with something else, not the € an not the ab, just the price. I tried several regexes but failed so far. The prices differ, but the structure stays the same.
Thanks!
Upvotes: 0
Views: 277
Reputation: 91498
I agree with stema about HTML parser, but if you really want to use regex, how about:
$str = preg_replace('/(class="special-price">.*?)\d+,\d+/s', "$1 55,00", $str);
Upvotes: 1
Reputation: 93026
If you really can't use a DOM/HTML parser and you are sure about the structure, you can try this
(class="special-price">.*[\r\n]{1,2}.*[\r\n]{1,2}[^\d]*)[\d,]+
and replace with $1
and your new price
See it here on Regexr
( # Start the capturing group
class="special-price">.*[\r\n]{1,2} # match from the "class="special-price""
.*[\r\n]{1,2} # match the following row
[^\d]*) # match anything that is not a digit and close the capt. group
[\d,]+ # Match the price
The part in the capturing group is stored in $1
, therefor tokeep this part you need to put it first into your replace string.
Upvotes: 2
Reputation: 2021
Now to change a text between two variables you can do the following:
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "ab 64,00 € *";
$parsed = get_string_between($fullstring, "ab ", "€ *");
echo $parsed; // (result = 64,00)
$newValue = $parsed + 10; //Do Whatever you want here
echo "ab " . $newValue . " € *"; // ab 74 € *
If you want to change the money format. money_format()
Please check this http://www.php.net/manual/en/function.money-format.php
You can change the numbers format and the way you would like them to be viewed in the page.
Upvotes: 1
Reputation: 5798
Try this,
preg_replace('/ab [0-9,] € */', 'ab NEW Value € *', $string)
where $string
contains html data.
Upvotes: 0