Search code examples
phpregexsubstringpreg-replacecurrency

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


I have a string which contains a price inside.

I need to remove the decimal part and currency part of that.

The currency symbol can be removed by PHP using the str_replace() function, but the decimal part varies from product to product.

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

I need this like:

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

I tried 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>');

But this only works when there are 00 decimals. Can someone help me with this?


Solution

  • You don't need more than one function call for this.

    Match the then zero or more non-digits, then capture one or more digits, then match anything that comes before the end span tag. Replace with the captured match.

    Code: (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+)[^<]*/","$1",$string);
    

    Output:

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