将 php 中单个字符串中包含的多个值相除

Divide multiple values contained in a single string in php

嗨,

我有这样的字符串:

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

我需要将每个值除以 100 得到如下结果:

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

所以我尝试了这个:

$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);

但我得到一个错误:

Warning: implode(): Invalid arguments passed

最简单的方法是什么?

您可以使用 preg_replace_callback 查找并替换所有数字除以 100 的值:

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