I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.
Because it hasn't been mentioned
if(preg_match('/^\d+\.\d+$/', $string)){
$float = (float)$string;
}
I think is_numeric is a better choice, but this works too.
What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.
^ start of string\d+ one or more digits\. the dot, literally\d+ one or more digits$ end of stringFor the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:
(...)? optional capture group, match this pastern 0 or 1 times.Which it should now be obvious is what makes the decimal optional.
Cheers!