phpstringfloating-pointtext-extractiontext-parsing

Get float value after £ symbol in a string and cast as a float type value


I have a system basically tracks finances. In this application it has a "cost" field (which unfortunately is VARCHAR field). This field has various values entered like:

£90
£210 per day
£50 per logo
Design - £180
£36 p/h
£1009.51

Is there any way I can convert these to floats? I tried just using (float) to juggle the type into a float, but it isn't working.


Solution

  • If it's always following a £ character, you can even make sure other numbers don't match:

    £\s*\d+(?:\.\d+)?
    

    Explanation

    £          # GBP
    \s*        # spaces, optional
    \d+        # digits, required (at least one)
    (?:        # non-capturing group 
      \.\d+    #   a literal dot, and more digits
    )?         # end group, make optional