PHP Developers Network
http://forums.devnetwork.net/

Regex to find $ amount and % amount in a string
http://forums.devnetwork.net/viewtopic.php?f=38&t=143203
Page 1 of 1

Author:  gmehta [ Fri Dec 09, 2016 11:04 am ]
Post subject:  Regex to find $ amount and % amount in a string

Hi,

I am working a requirement where I need to extract the $ amount or % amount from a string. I have been able to extract dollar amount successfully using the following regex pattern

$pattern = '/\$[0-9]*\.{0,1}[0-9]+/';

I still however need help with finding % amount using the same regex. Can someone please help.

Example:

5% Off Your Order --> Need to get 5% from this
5.25% Off All Orders --> Need to get 5.25% from this
$10 Off Orders Over $100 --> Need to get $10, $100

Can someone please help me with the Regex.

Author:  Christopher [ Fri Dec 09, 2016 12:07 pm ]
Post subject:  Re: Regex to find $ amount and % amount in a string

Why don't you just match [0-9\.] and return all matches. That will work for your case. For any decimal number search for regexps e.g. \d+(\.\d{1,2})?

Author:  requinix [ Fri Dec 09, 2016 7:06 pm ]
Post subject:  Re: Regex to find $ amount and % amount in a string

Is there a risk of the string containing numbers that aren't money or percentages?

Anyway, what happened when you tried a regex for the percentage? All you needed to do was replace the $ at the beginning for a % at the end...

Author:  gmehta [ Sun Dec 11, 2016 2:15 am ]
Post subject:  Re: Regex to find $ amount and % amount in a string


Author:  requinix [ Sun Dec 11, 2016 2:20 am ]
Post subject:  Re: Regex to find $ amount and % amount in a string

You need to move that backslash too. The \ and $ are a pair, and together they represent a literal $ symbol.

Page 1 of 1 All times are UTC - 5 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/