我有一个字符串,其中包含几个不同的价格。这是字符串:
<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,而不是欧元,不是ab,只是价格。我尝试了几个正则表达式,但到目前为止都失败了。价格不同,但结构保持不变。
谢谢!
如果你真的不能使用DOM/HTML解析器,并且你对结构很确定,你可以试试这个
(class="special-price">.*['r'n]{1,2}.*['r'n]{1,2}[^'d]*)['d,]+
并替换为$1
和您的新价格
在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
捕获组中的部分存储在$1
中,因此要保存该部分,您需要首先将其放入替换字符串中。
我同意stema关于HTML解析器的观点,但如果你真的想使用regex,那么:
$str = preg_replace('/(class="special-price">.*?)'d+,'d+/s', "$1 55,00", $str);
现在要在两个变量之间更改文本,可以执行以下操作:
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/en/function.money-format.php
您可以更改数字格式以及希望在页面中查看数字的方式。
试试这个,
preg_replace('/ab [0-9,] € */', 'ab NEW Value € *', $string)
其中CCD_ 3包含html数据。