[英]Replace only last number (price) in a string using regex and PHP?
我有一个包含几个不同价格的字符串。 这是字符串:
<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>
我只想用其他东西代替27,00,而不是€a不是ab,只是价格。 我尝试了几个正则表达式,但到目前为止都失败了。 价格不同 ,但结构保持不变。
谢谢!
如果您确实无法使用DOM / HTML解析器,并且对结构有把握,则可以尝试以下操作
(class="special-price">.*[\r\n]{1,2}.*[\r\n]{1,2}[^\d]*)[\d,]+
并替换为$1
和您的新价格
( # 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
捕获组中的部分存储在$1
,因此要保留此部分,您需要先将其放入替换字符串中。
现在要在两个变量之间更改文本,您可以执行以下操作:
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 € *
如果要更改货币格式。 money_format()
请检查此http://www.php.net/manual/zh/function.money-format.php
您可以更改数字格式以及希望在页面中查看它们的方式。
我同意HTML解析器的说法,但是如果您真的想使用regex,该如何做:
$str = preg_replace('/(class="special-price">.*?)\d+,\d+/s', "$1 55,00", $str);
尝试这个,
preg_replace('/ab [0-9,] € */', 'ab NEW Value € *', $string)
其中$string
包含html数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.