0

I have following grouped currency formatted string:

$str = "$1,000,000";

I want to just extract 1000000 in order to do some calculation. How can I achieve that? Is there any built-in PHP function to do so? Otherwise I may need to use some RegExp.

EDIT

This is not a duplicate question because here we have a currency grouped formatted string and not a straightforward simple text.

2

2 Answers 2

4

You might replace all non-digits with the empty string:

$str = "$1,000,000";
print(
  preg_replace('/\D+/', '', $str)
);

Of course, "non-digits" includes decimal points too. If you want to keep decimal points, then use a negated character set instead:

$str = "$1,000,000.00";
print(
  preg_replace('/[^\d.]+/', '', $str)
);
Sign up to request clarification or add additional context in comments.

11 Comments

In \D+, is + necessary? I'm getting the same result even after removing it.
No, it's not necessary, but it might be a bit more efficient. For example, with $$$$5, rather than replacing a single $ 4 times, it'll just replace $$$$ once.
I think you are not right because if i had $$$1,000,000 then result still would be 1000000 without using + in \D
The result will be the same, but there will be fewer operations on the string performed to get to that result. Like I said, it's not necessary, just more efficient.
@user5307298 + is one or more, without the quantifier you replace each character individually. Quantified is more efficient (although minimal in your example) see regex101.com/r/WbZnMk/2 vs regex101.com/r/WbZnMk/1
|
1

Here is a str_replace way, assuming that your digits only contain $ and , (or . if you include decimals)

$toBeRemoved = array('$', ',');
$str = '$1,000,000';
$cleaned = floatval(str_replace($toBeRemoved, "", $str));
echo $cleaned;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.