Search code examples
phpregexstringfloating-pointtext-extraction

Get float value without its unit of measure from a string


I've a list of strings of the following type:

27 km
56.1 km
45 KM
96.2km
87 k

And I want to get the numeric value for each one. As you can see some of them are float values, and the suffix "km" sometimes is mistyped. The output I'm looking for is the following:

27
56.1
45
96.2
87

I've found regular expressions on the web that convert a string to number but they don't consider that some values can be float, how can I write a function or find a expression that meets my requirements?


Solution

  • $var = floatval($float); is what you're looking for.