SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2005
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using preg_match to get currency amount

    Hello, I am new to using preg_match and I can't figure out how to do this. I have a string of text that ends with the cost of the product. It looks like this:

    Blah, blah, blah for $10.95

    I only need the cost. I am sure this is a really easy one but I have tried several different preg_match statements to only pull out the cost but nothing seems to do it.

    Thanks for any help.

  2. #2
    SitePoint Zealot
    Join Date
    Aug 2005
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is the cost always at the very end of the string? Or can it be elsewhere in the string?

  3. #3
    SitePoint Zealot
    Join Date
    Dec 2005
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For this merchant, it is always at the end and always preceeded by a $. Thanks

  4. #4
    SitePoint Enthusiast duckax's Avatar
    Join Date
    Aug 2005
    Posts
    94
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you just want to remove the $, using str_replace or substr would be much easier and faster.

    If you have a whole bunch of costs you want to match in a string eg "Apples: $1.99 Orange: $2.99", then the regular expression you need is '/\$[0-9]+\.[0-9]+/'

  5. #5
    SitePoint Zealot
    Join Date
    Aug 2005
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think this will work then.

    PHP Code:
    $_value 'The cost of this product is $1.96';
    $_pattern '/\$\d*\.\d{2}$/';

    $_matchcount preg_match($_pattern$_value$_matches);
    if (
    $_matchcount 0)
    {
        
    $_cost $_matches[0];


  6. #6
    SitePoint Zealot
    Join Date
    Dec 2005
    Posts
    119
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, works great! You guys are awesome!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •