簡體   English   中英

使用正則表達式和PHP僅替換字符串中的最后一個數字(價格)?

[英]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和您的新價格

在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 ,因此要保留此部分,您需要先將其放入替換字符串中。

現在要在兩個變量之間更改文本,您可以執行以下操作:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM