Search code examples
phpmysqlkohana

Can't remove whitespaces in string


My script reads txt file and then writes values into database table. There is a field with price, and in txt file price with 4 digit values have whitespace after first digit (2 500 ex.). I put this function (str_replace works well and replaced ',' but when I use it for removing whitespace it does not do it, and finally I put preg_replace but it also skips whitespace):

$model->price = preg_replace('/\s+/','',str_replace(',', '.', $row_data[3]));

datatype of price field in my table is varchar, when I used int or decimal it skips digits after space (2 070 becomes 2, 12 015 => 12). I have to remove this space in integration stage, because when I do operations with price field php skips digits after space and I have errors in my further manipulations.

What is the problem guys?

UPD Solution from @jeroen works great, I changed field of price to decimal (10,2) and put this line for parsing the string with price:

$model->price = filter_var(str_replace(',', '.', $row_data[3]), FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); 

Solution

  • I would not use a regex but a filter for that:

    // 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 should make sure that you update all your prices in the database so that you can switch to a numerical value in the database itself.