Categories

Could It Really Be That Easy?

In a project we are working on we needed a way to extract the number portion of a weight from a string. So we could receive any of the following:

21
21 lbs
21.3
21.3 lbs

We started looking into some regular expressions to do the job, but then ran across a page saying that you can just cast it to a float or int and it will drop the string bit automatically like so:

<?php
$string = “22.8 lbs”;
echo (float)$string;
?>

<?php
$string = “22.8 lbs”;
echo (float)$string;
?>

This should output 22.8. Not perfect for every situation, but pretty handy in the right one.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>