// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
// return 0 if the string contains no number at all or is not a string:
if (!is_string($string) || !preg_match('/d/', $string)) {
return 0;
}
// Replace all ',' with '.':
$workingString = str_replace(',', '.', $string);
// Keep only number and '.':
$workingString = preg_replace("/[^0-9.]+/", "", $workingString);
// Split the integer part and the decimal part,
// (and eventually a third part if there are more
// than 1 decimal delimiter in the string):
$explodedString = explode('.', $workingString, 3);
if ($explodedString[0] === '') {
// No number was present before the first decimal delimiter,
// so we assume it was meant to be a 0:
$explodedString[0] = '0';
}
if (sizeof($explodedString) === 1) {
// No decimal delimiter was present in the string,
// create a string representing an integer:
$workingString = $explodedString[0];
} else {
// A decimal delimiter was present,
// create a string representing a float:
$workingString = $explodedString[0] . '.' . $explodedString[1];
}
// Create a number from this now non-ambiguous string:
$number = $workingString * 1;
return $number;
}
Code Example |
---|
Php :: php foreach alternative syntax |
:: |
:: increase php memory |
Php :: |
Php :: laravel module make migration |
Php :: softdeletes laravel |
:: |
Php :: php preg match space or start of string |
:: php unlink |
Php :: |
:: laravel destroy or delete |
Php :: symfony set timezone |
Php :: file could not be downloaded: Unable to find the wrap per "https" - did you forget to enable it when you configured PHP? failed to open stream: No such file or directory |
:: use font awesome in laravel 8 |
Php :: - root composer.json requires php ^7.2 but your php version (8.0.1) does not satisfy that requirement. |
:: |
:: |
Php :: |
:: json encode decode php |
:: |
:: |
Php :: php image resize |
Php :: |
Php :: laravel get from model first |
Php :: load-styles.php 403 |
Php :: eloquent get record older than 2 days |
:: |
Php :: |
Php :: |
:: |