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
?
R开发者_C百科eason 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.
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.
try this:
$price_data = "Now £193.95";
list($t, $price) = explode('£',$price_data);
//$price should now contain 193.95
here is a demo: http://codepad.org/az87F5wA
Financial data should be stored as integers, not floats due to loss of precision with floating datatypes: http://en.wikipedia.org/wiki/Precision_(computer_science)
Therefore, you should store it in MySQL as an integer (representing cents) using the following code to extract only the digits:
$subject = 'Now £193.95';
preg_match_all('/\\d/', $subject, $result, PREG_PATTERN_ORDER);
$result = implode( '', $result[0] );
if( !empty($result) ){
$result = intval($result);
}else{
$result = 0;
}
var_dump( $result );
Also, be careful when you perform division on integer types because you can "lose cents".
HTH
精彩评论