Search code examples
phpvariablesstrip

Stripping out text characters from variables, leaving numbers and comma?


I need to be able to strip from characters from a few variables leaving only the numbers and the £ sign (unless of course mysql can add that in itself?) and also any . separators.

so if the variable $price_data contains

Now £193.95

How do I end up with

193.95 ?

Reason I need this done is I need to be able to insert the data into the field as decimal, and be able to arrange it from least to most expensive.


Solution

  • Depending on the input data it might be more reliable to remove any leading or trailing non-numbers:

    $price = preg_replace('_^\D+|\D+$_', "", $price_data);
    

    This leaves in the dot if enclosed by numbers, and would work with a literal £ as well as the £ escape, and removes any trailing garbage.