如何从欧元 (€) 表达式中删除特定的前导和尾随字符?

How to remove specific leading and trailing characters from Euro (€) expression?

我有一个包含价格的字符串。

我需要删除其中的小数部分和货币部分。

可以使用str_replace()函数PHP删除货币符号,但小数部分因产品而异。

<span class="price" id="old-price-3">€&nbsp;200,00 </span>
    <span class="price" id="product-price-3">€&nbsp;80,00</span>

我需要这样的:

<span class="price" id="old-price-3">200 </span>
        <span class="price" id="product-price-3">80</span>

我试过了str_replace():

echo str_replace(array(',00','€'),'','<span class="price" id="old-price-3">200 </span>
                <span class="price" id="product-price-3">80</span>');

但这仅在有 00 位小数时有效。有人可以帮我解决这个问题吗?

您可以使用这个正则表达式:

/€&nbsp;([0-9]+),([0-9]+)/

详情:

€&nbsp;   start the match with € and a space
([0-9]+)  match any digit 1 or more times
,         match a comma after the first number
([0-9]+)  match any digit 1 or more times after the comma

像这样:

<?php
$s = '<span class="price" id="old-price-3">€&nbsp;200,00 </span>
<span class="price" id="product-price-3">€&nbsp;80,00</span>';
var_dump(htmlentities(preg_replace("/€&nbsp;([0-9]+),([0-9]+)/", "", $s)));

Demo

为此您不需要调用多个函数。

匹配 然后零个或多个非数字,然后捕获一个或多个数字,然后匹配结束范围标记之前的任何内容。替换为捕获的匹配项。

代码:(Demo) (Pattern Demo)

$string='<span class="price" id="old-price-3">€&nbsp;200,00 </span>
<span class="price" id="product-price-3">€&nbsp;80,00</span>';

echo preg_replace("/€\D*(\d+)[^<]*/","",$string);

输出:

<span class="price" id="old-price-3">200</span>
<span class="price" id="product-price-3">80</span>