我有一个像这样的字符串
$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'";
答案 0 :(得分:3)
类似的东西:
$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);
答案 1 :(得分:2)
假设原始数组定义为
$coords="429, 457, 421, 460, 424, 464, 433, 465, 433, 460";
您可以使用explode,array_map和implode执行此操作。请注意,此处使用的匿名函数仅适用于php 5.3及更高版本。
$newCoords = implode(", ",array_map(function($a) { return $a *2; }, explode(",", $coords)));
答案 2 :(得分:1)
上述示例中的工作代码...请注意“to”
引用中的更改$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.'"';
答案 3 :(得分:0)
您可以先删除所有不需要的文本,然后像这样调用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"