-1

我有一个这样的字符串

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

我想将数字乘以 2,如何编写一个简单的 php 代码来进行计算?

这个新的 $coordinate 应该是

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'";

4

4 回答 4

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);
于 2013-08-26T04:41:17.553 回答
2

假设您的原始数组定义为

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

您可以使用explodearray_mapimplode来做到这一点。请注意,此处使用的匿名函数仅适用于 php 5.3 及更高版本。

$newCoords = implode(", ",array_map(function($a) { return $a *2; }, explode(",", $coords)));
于 2013-08-26T04:42:17.837 回答
1

上面示例中的工作代码...注意引号中从 " 到 ' 的更改

$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.'"';
于 2013-08-26T04:45:52.590 回答
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"
于 2013-08-26T04:50:50.233 回答