简体   繁体   中英

Replace only last number (price) in a string using regex and PHP?

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!

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.

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.

我同意HTML解析器的说法,但是如果您真的想使用regex,该如何做:

$str = preg_replace('/(class="special-price">.*?)\d+,\d+/s', "$1 55,00", $str);

Try this,

preg_replace('/ab [0-9,] € */', 'ab NEW Value € *', $string)

where $string contains html data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM