RegEx – How to Extract Price?

How would I extract the dollar amount from the following string

“some text will go here and more and more and then there will be some price $34.03 but that doesn’t mean the string will end”

I want to extract $34.03…also want to extract if there is no cents

“some text will go here and more and more and then there will be some price $34 but that doesn’t mean the string will end”

Here I want to extract $34

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I’m no regex-guru, but was able to whip up the following with RegExr.

/(\$[0-9]+(\.[0-9]{2})?)/

Matches $35.03 and $35. To accept formats like $35,000.52 you would need to include ,

/(\$[0-9,]+(\.[0-9]{2})?)/

This could likely be improved upon, but from my preliminary tests, it works just fine.

Solution 2

'/\$\d+(?:\.\d+)?/'

if(preg_match('/\$\d+(?:\.\d+)?/',$text,$matches)){
    echo $matches[0]; //which would be $34 or $34.03
}

Solution 3

Since you don’t mention a specific regex engine, you might have to adjust this a bit:

/(\$\d+(\.\d+)?)/

Solution 4

What about this regexp: \$[0-9.,]+ or \$([0-9.,]+) to strip the $?

It’s simple but it does pretty much what you want, it even catches things like this: $1,450.8934 or $14.343.

Of course the drawback it’d be that it’d catch $34.54.23 as well.

Or if you want to catch only two decimals: \$[0-9,]+\.[0-9]{2} it’d catch the $5.23 part of $5.234565.

You can use it with preg_match or preg_match_all.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply