简体   繁体   English

使用正则表达式和PHP仅替换字符串中的最后一个数字(价格)?

[英]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. 我只想用其他东西代替27,00,而不是€a不是ab,只是价格。 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 如果您确实无法使用DOM / HTML解析器,并且对结构有把握,则可以尝试以下操作

(class="special-price">.*[\r\n]{1,2}.*[\r\n]{1,2}[^\d]*)[\d,]+

and replace with $1 and your new price 并替换为$1和您的新价格

See it here on Regexr 在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. 捕获组中的部分存储在$1 ,因此要保留此部分,您需要先将其放入替换字符串中。

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() money_format()

Please check this http://www.php.net/manual/en/function.money-format.php 请检查此http://www.php.net/manual/zh/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. 其中$string包含html数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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