note 76537 added to function.floatval
| From: | leprau at leprau dot de | Date: | Thu, 19 Jul 2007 16:26:03 +0000 |
| Subject: | note 76537 added to function.floatval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128733@lists.php.net to get a copy of this message | ||
For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string "Price: 123,45$"
If no useable value is found, the function returns false.
Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)
12,.3 will return 12
1,000,000 will return 1000.0 !
(if thousands separator is defined,
decimals should be defined too ...
in fact I was too lazy to check for that too)
Here you go, and feel free to optimize the function ;)
<?php
function getFloat($pString) {
if (strlen($pString) == 0) {
return false;
}
$pregResult = array();
$commaset = strpos($pString,',');
if ($commaset === false) {$commaset = -1;}
$pointset = strpos($pString,'.');
if ($pointset === false) {$pointset = -1;}
$pregResultA = array();
$pregResultB = array();
if ($pointset < $commaset) {
preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
}
preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
|| strstr($preResultA[0],$pregResultB[0]) == 0
|| !$pointset))) {
$numberString = $pregResultA[0];
$numberString = str_replace('.','',$numberString);
$numberString = str_replace(',','.',$numberString);
}
elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
|| strstr($pregResultB[0],$preResultA[0]) == 0
|| !$commaset)) {
$numberString = $pregResultB[0];
$numberString = str_replace(',','',$numberString);
}
else {
return false;
}
$result = (float)$numberString;
return $result;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 212.202.174.237
----
Manual Page -- http://www.php.net/manual/en/function.floatval.php
Edit -- https://master.php.net/note/edit/76537
Del: integrated -- https://master.php.net/note/delete/76537/integrated
Del: useless -- https://master.php.net/note/delete/76537/useless
Del: bad code -- https://master.php.net/note/delete/76537/bad+code
Del: spam -- https://master.php.net/note/delete/76537/spam
Del: non-english -- https://master.php.net/note/delete/76537/non-english
Del: in docs -- https://master.php.net/note/delete/76537/in+docs
Del: other reasons-- https://master.php.net/note/delete/76537
Reject -- https://master.php.net/note/reject/76537
Search -- https://master.php.net/manage/user-notes.php