Cain Nuke Cain Nuke - 5 months ago 9
PHP Question

Divide multiple values contained in a single string in php

Hi,

I have a string like this:

$coord = "1,0 1,8 7,13 7,94";


and I need to divide by 100 each one of the values to get something like this:

0.01,0 0.01,0.08 0.07,0.13 0.07,0.94


So I tried this:

$pair=explode(" ", $coord);

foreach ($pair as $val) {
$sing = explode(",", $val);
foreach ($sing as $div) {
$res = ($div/100);
}
$sing_d = implode(",", $res);
}

$result = implode(" ", $sing_d);

print ($result);


but I get an error:

Warning: implode(): Invalid arguments passed


What is the simplest way to do this?

Answer

You could use preg_replace_callback to find and replace all numbers by their value divided by 100:

$result = preg_replace_callback("/\d+(\.\d+)?/", function ($match) {
    return $match[0]/100;
}, $coord);