Can't remove spaces in string
My script reads a txt file and then writes the values to a database table. There is a field with a price, and in txt the price of a file with 4-digit values has a space after the first digit (2,500 copies). I put this function in (str_replace works well and is replaced by "," but when I use it to remove spaces it doesn't, and finally I put preg_replace but it also skips spaces):
$model->price = preg_replace('/\s+/','',str_replace(',', '.', $row_data[3]));
The type of the price field in my table is varchar, when I used int or decimal it skips digits after the space (2070 becomes 2, 12 015 => 12). I have to remove this space in the integration stage, because when I do operations with the price field, php skips the numbers after the space and I have errors in my further manipulations.
What is the problem?
UPD Solution from @jeroen works great, I changed the price field to decimal (10,2) and put this line to parse the price string:
$model->price = filter_var(str_replace(',', '.', $row_data[3]), FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
source to share
I wouldn't use a regex, but filter for this:
// replace if necessary
$number = str_replace(',', '.', $row_data[3]);
// filter unwanted characters
$model->price = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
And you have to make sure that you update all of your prices in the database so that you can switch to a numeric value in the database itself.
source to share