Gareth
Gareth

Reputation: 1

str_replace not doing what I need it to

I have a form that uses jQuery to calculate totals before submission. It sends the total along with the currency symbol to the form handling script. This is generating some

Warning: A non-numeric value encountered

messages, so I have been using str_replace. However, the following code is still generating the errors. It works everywhere else apart from this one section of code and I cannot find a solution. Could anyone help with some advice.

function netprice() {
    $vatrate = 1.2;
    $gross = str_replace('£','',$_POST['unit_Price']);
    $net = round(($gross / $vatrate) , 2);

    if (empty($gross)) {
        echo"-";
    }else{
        echo $net;
    }
}

Upvotes: -2

Views: 165

Answers (6)

Gareth
Gareth

Reputation: 1

Thanks for all your help guys. I went with Pejka's solution

$gross = floatval(preg_replace('/[^0-9,.]/', '', $_POST['unit_Price']));

I really appreciate all your help. A thousand thanks :)

Upvotes: 0

Chris Toxz
Chris Toxz

Reputation: 13

Change £ to £

Also check your output, which data contains $gross after str_replace

Upvotes: 0

TheMY3
TheMY3

Reputation: 353

You can use filter_var function to get only number from string.

$gross = filter_var($_POST['unit_Price'], FILTER_SANITIZE_NUMBER_INT);

If you want to get float use:

$gross = filter_var($_POST['unit_Price'], FILTER_SANITIZE_NUMBER_FLOAT);

Upvotes: 2

aperpen
aperpen

Reputation: 728

If your currency symbol is before the value, you can use a substr:

<?php
$price = substr('£1.2', 2); //1.2

Note that because £ symbol is an special char you must substract 2 first chars. You can check it by doing a var_dump

If your currency symbol is at the end, you can simply force de value to be float:

$price = (float)'1.2£'; //1.2

Upvotes: 0

Pejka
Pejka

Reputation: 141

You really shouldn't send the currency symbol with the form. If you cannot avoid it, there may be other characters such as a space between the symbol and the number. First off you could try passing the resulting value through floatval() like such:

$gross = floatval(str_replace('£','',$_POST['unit_Price']));

If it still doesn't work, use regex instead to strip every character except for numbers, commas and dots:

$gross = floatval(preg_replace('/[^0-9,.]/', '', $_POST['unit_Price']));

Upvotes: 1

naui95
naui95

Reputation: 31

Instead of using str_replacethat could be leaving spaces or other chars, you could use preg_replaceas in the example here Remove non-numeric characters (except periods and commas) from a string

your code would look like this:

function netprice() {

$vatrate = 1.2;

$gross = preg_replace("/[^0-9,.]/", "", $_POST['unit_Price']);
$net = round(($gross / $vatrate) , 2);

    if (empty($gross)) {

        echo"-";

    }else{

        echo $net;
    }
}

preg_replace will strip out all chars except for those defined in the first argument.

Upvotes: 2

Related Questions