从字符串中获取数字,然后进行计算


get the number from a string then do the calculation

我有一个类似的字符串

$coordinate = "coords='429, 457, 421, 460, 424, 464, 433, 465, 433, 460'";

我想把数字乘以2,如何写一个简单的php代码来做这个计算?

这个新的$坐标应该是

coords="858, 914, 842, 920, 848, 928, 866, 930, 866, 920"

我的原始字符串是"alt='Japan' shape='poly' coords='429, 457, 421, 460, 424, 464, 433, 465, 433, 460'";

类似于:

$coords="429, 457, 421, 460, 424, 464, 433, 465, 433, 460";
$coords_arr = explode(",", $coords);
array_walk($coords_arr, 'alter');
function alter(&$val) {
    $val *= 2; //multiply by 2
}
print_r($coords_arr);

更新代码::

$coordinate = "coords='429, 457, 421, 460, 424, 464, 433, 465, 433, 460'";
$arr = explode("=", $coordinate);
$data = trim($arr[1], "'"); //remove quotes from start and end
$coords=explode(",", $data);
array_walk($coords, 'alter');
function alter(&$val) {
    $val = (int) $val * 2;
}
echo "<pre>";
print_r($coords);

假设原始数组定义为

 $coords="429, 457, 421, 460, 424, 464, 433, 465, 433, 460";

您可以使用爆炸、array_map和内爆来完成此操作。请注意,此处使用的匿名函数仅适用于php5.3及以上版本。

$newCoords = implode(", ",array_map(function($a) { return $a *2; }, explode(",", $coords)));

正在使用上面示例中的代码。。。注意报价从"到"的变化

$coordinate = 'coords="429, 457, 421, 460, 424, 464, 433, 465, 433, 460"';
$start = strpos($coordinate,'"');
$end = strrpos($coordinate,'"');
$str = substr($coordinate,$start + 1, ($end - $start -1));
$val_a = explode(', ',$str);
$new_str = '';
foreach ($val_a as $val_1) {
    $val_i = (int)$val_1 * 2;
    if ($new_str) $new_str .= ", $val_i";
    else $new_str = "$val_i";
}
echo 'coords="'.$new_str.'"';

您可以先去掉所有不需要的文本,然后调用array_map,如下所示:

$coordinate = "coords='"429, 457, 421, 460, 424, 464, 433, 465, 433, 460'"";
$s = preg_replace('/coords's*='s*"([^"]+)"/', '$1', $coordinate);
$coordinate = 'coords="' . implode(", ", array_map(function($n) {return $n*2;}, 
               explode(",", $s))) . '"';
echo $coordinate . "'n";
//=> coords="858, 914, 842, 920, 848, 928, 866, 930, 866, 920"