I have to search through an Excel file and get the numbers that have a comma as a decimal point and convert it to a decimal point.(ex: 23,56 -> 23.56, 23123,566 -> 23123.566). I have already exported the excel file to .csv and put all contents into arrays but I have trouble finding the numbers with comma. This is how one of my array looks like:
Array
(
[A1] => 1
[A2] => 123123
[A3] => dasdadwa
[A4] => 6,7
[A5] => 24f,5
[A6] => f5,5
[A7] => dasdad,fsdfsdfsfsasada dasdasd
[A8] => aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
[A9] => dasdasd
[A10] => q231e
[A11] =>
[A12] => 0
[A13] =>
[A14] =>
[A15] => 1
[A16] => 123123
[A17] => dasdadwa
[A18] => 6,7
[A19] => 24f,5
[A20] => f5,5
[A21] => dasdad,fsdfsdfsfsasada dasdasd
[A22] =>
[A23] =>
[A24] => q231e
[A25] =>
[A26] => 0
[A27] =>
[A28] =>
[A29] => 1
[A30] => 123123
[A31] => dasdadwa
[A32] => 6,7
[A33] => 24f,5
[A34] => f5,5
[A35] => dasdad,fsdfsdfsfsasada dasdasd
[A36] =>
[A37] =>
[A38] => q231e
[A39] =>
[A40] =>
[A41] =>
[A42] =>
)
I'm only interested in the characters that have only numbers and a comma but it is troublesome because those entries are strings. I have tried messing with regex but I just could not get it to work. Here is what i have so far:
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$contents = csv_to_array($filename.'.csv');
foreach($contents as $val)
{
//If $val is a number separated by comma
//Replace comma with . (str_replace(',','.');, $val);)
}
Just simple pattern which will replace only your pattern:
//rest od your code and now:
foreach($contents as $key => $val)
{
$contents[$key] = preg_replace('/^(\d+),(\d+)$/', '\1.\2', $val);
}
This code will touch only strings like 2,3
. Strings like this ff,333
will not be touch
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments