How to simplify the use of str_replace

Asked

Viewed 168 times

1

As I explained in this question, I’m using the maskMoney to generate a coin mask in multiple fields input of type="text", only when I perform arithmetic operations with the values obtained, and then use the number_format in output, it gives various types of problem in formatting (does not include comma, etc).

The solution I found on that topic was the following:

$ultsalbase = $_POST["Tultsal"]; 

$ultsalbase2 = str_replace('.', '', $ultsalbase); 
$ultsalbase3 = str_replace(',', '.', $ultsalbase2);

Thus, when the value enters the form in the format 1.000,00, the str_replacetransforms it to 1000.00. Then after making the calculations, the number_format returns currency values correctly (1,000.00).

What happens is that since there are many fields, I think it might be wrong to have to create two new variables for each field, just to be able to change the formatting.

There is no simpler solution to this?

I tried that:

$ultsalbase = $_POST["Tultsal"] . str_replace('.', '', $ultsalbase) . str_replace(',', '.', $ultsalbase); 

But it didn’t work. Any idea?

1 answer

1


Create a function to apply to all necessary items from $_POST, for example:

function formatFromMaskMoney($value) {
    $value = str_replace(' ', '', $value);
    $value = str_replace('.', '', $value);
    $value = str_replace(',', '.', $value);
    return (double) $value;
}

$_POST["variavel-1"] = formatFromMaskMoney($_POST["variavel-1"]);
$_POST["variavel-2"] = formatFromMaskMoney($_POST["variavel-2"]);
$_POST["variavel-3"] = formatFromMaskMoney($_POST["variavel-3"]);
$_POST["variavel-4"] = formatFromMaskMoney($_POST["variavel-4"]);

//exemplo:
echo number_format(formatFromMaskMoney('4.233.456.700, 99') / formatFromMaskMoney('1.000.000,00'), 2, ",", ".");

Or if you want to make it easier you can apply one array and use array_map, just as:

function formatFromMaskMoney($key) {
    if (isset($key) && isset($_POST[$key])) {
        $_POST[$key] = str_replace(' ', '', $_POST[$key]);
        $_POST[$key] = str_replace('.', '', $_POST[$key]);
        $_POST[$key] = (double) str_replace(',', '.', $_POST[$key]);
    }

    return $key;
}

$posts = array('variavel-1', 'variavel-2', 'variavel-3', 'variavel-4');
array_map('formatFromMaskMoney', $posts);

echo number_format($_POST['variavel-1'] / $_POST['variavel-2'], 2, ",", ".");

And you can also make the function check if the field is a value of money and apply the str_replace:

function formatFromMaskMoney($value) {
    if (preg_match('/^[0-9.]+[,]( |)\d{2}$/', $value) !== 0) {
        $value = str_replace(' ', '', $value);
        $value = str_replace('.', '', $value);
        $value = (double) str_replace(',', '.', $value);
    }

    return $value;
}

$_POST = array_map('formatFromMaskMoney', $_POST);
print_r($_POST);//Para verificar os dados antes de usa-los.

echo number_format($_POST['variavel-1'] / $_POST['variavel-2'], 2, ",", ".");

Online example on ideone: https://ideone.com/HScQXG

  • Vixi, that was the jet! Thanks! (I used the first option)

  • So the other way worked perfectly, but this looks much more elegant! : ) I’m trying here, and it includes automatic all number_format (very cool! ), but the variables that solve the artimetic operations appear without formatting, and with error in the calculation. Ah, and at the suggestion of the IDE I’ve changed where it is key for value, then it worked, but as I said above...

  • Yeah, the last one. Thanks!

  • So the calculation error persists, but if I take out the function $value = number_format($value, 2, ',', '.'); of the function, hence it converts from the maskmoney and makes the calculations right. It is better to create two functions, a pro maskmoney and another pro number_format? Because it looks like he’s doing everything "all at once", before making the calculation... Cara was worth a lot for the help, every day I am more impressed with the quality of the answers here at Sopt.

  • So, still persists... I need to leave now, later I will do some tests here to see if the problem is not in my code, and put the results... Thanks for now! Hugs!

  • @gustavox vacillatlo my confused the array_map, with another array function for PHP, the correct use is $_POST = array_map('formatFromMaskMoney', $_POST);, edited the answer.

  • So what happens is that variables that don’t come from the form, that only perform operations, for example: With $ultsalbase = formatFromMaskMoney ($_POST ["Tultsal"]); take the value of the form. And with $remmes = formatFromMaskMoney($ultsalbase) step it to another variable. Then I have a variable $multipl whose value is 220. Hence $remhora = formatFromMaskMoney($remmes / $multipl); calculations go wrong. But when I take the number_format of the function', and put right at the exit, there is perfect...

  • I got it so you just need the number_format at the end, see my issue, calm down and.

  • In the above case, for example, the output with the field in the form "Tultsal" filled in 2.800,00 and the multiplier in 220, the output should be R $ 12,73 (what comes out if the number_format function'). But with it in function R $ 1,38. O var_dump returns: float(1.375)

  • @gustavox think number_format can only be used after the calculation, so I updated the response and added some examples of how to proceed.

  • That’s right! Now it’s perfect, and you don’t even need the first$value = str_replace(' ', '', $value); and of (double) at last value. It’s perfect, really worth!

  • @gustavox the str_replace is only to facilitate and the double is to convert the string into numeric. But in PHP the variables are dynamic so really double is not necessary, but I recommend removing the spaces. Good night

  • Okay, include it again here. Good night to you too and thank you again! Hug!

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.