I have a string like this:
$string = 'e.g. 25.32';
I want to pull out only the number (25.32)
The text surrounding the number could potentially be any non-number.
You could use regular expressions if you know the format of your string with preg_match
You could use something like :
<?php
$str = "e.g. 25";
$val = (int)$str;
?>
But it's not the best solution.
A "stronger" and universal alternative is...
Code : (UPDATED)
<?php
$str = "e.g. 25.32";
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
$val = $matches[0];
echo $val;
?>
Output :
25.32
As a function : (UPDATED)
<?php
function getInt($str)
{
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
return $matches[0];
}
?>
Usage :
<?php
$val = getInt("e.g. 25.32");
?>
My old function that also works with negative numbers:
function getNumber($str){
return floatval(preg_replace('/^[^\d-]+/','',$str));
}
If the number is simple:
([0-9]+(?:\.[0-9]+)?)
You then want to match this at the end of the string:
$string = 'e.g. 25.32';
$number = preg_replace('~^.*?([0-9]+(?:\.[0-9]+)?)$~', '$1', $string);
This will make $number
contain "25.32"
, convert it to float if you need the float value:
$float = (float) $number;
This code does only work if there actually is a number. If you can't be sure it is, test first:
$string = 'e.g. 25.32';
$number = NULL;
$hasNumber = preg_match('~([0-9]+(?:\.[0-9]+)?)$~', $string, $matches);
if ($hasNumber)
{
list(, $number) = $matches;
}
If the number can be a number as in PHP:
([+-]?INF|[+-]?(([0-9]+|([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*))|([0-9]+|(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))[eE][+-]?[0-9]+))
So take care what you actually need to match.